blob: 24dcf28f92f0deba747135f059cbd58ad2431d07 [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;
Michael Groover73f69482023-01-27 11:01:25 -0600110import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800111import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800112import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800113import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700114import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700115import android.app.admin.DevicePolicyManager;
junyulaie7c7d2a2021-01-26 15:29:15 +0800116import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700117import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800118import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800119import android.content.ContentResolver;
120import android.content.Context;
121import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700122import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800123import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700124import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900125import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900126import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700127import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800128import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800129import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800130import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900131import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800132import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900133import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900134import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800135import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900136import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800137import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700138import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900139import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800140import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800141import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800142import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800143import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800144import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900145import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900146import android.net.INetworkMonitor;
147import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900148import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900149import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700150import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800151import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900152import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900153import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900154import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800155import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100156import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800157import android.net.NativeNetworkConfig;
158import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800159import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700160import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700161import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900162import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700163import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800164import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700165import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900166import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900167import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000168import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900169import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700170import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900171import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700172import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900173import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700174import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800175import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900176import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700177import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000178import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800179import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900180import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800181import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400182import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700183import android.net.QosCallbackException;
184import android.net.QosFilter;
185import android.net.QosSocketFilter;
186import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700187import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800188import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800189import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800190import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900191import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400192import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800193import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800194import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400195import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800196import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900197import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900198import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900199import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800200import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900201import android.net.networkstack.ModuleNetworkStackClient;
202import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900203import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800204import android.net.resolv.aidl.DnsHealthEventParcel;
205import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
206import android.net.resolv.aidl.Nat64PrefixEventParcel;
207import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900208import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900209import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800210import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800211import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800212import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700213import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000214import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800215import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700216import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700217import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800218import android.os.Looper;
219import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700220import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700221import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900222import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800223import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700224import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700225import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800226import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700227import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900228import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900229import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700230import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700231import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400232import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800233import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900234import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700235import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700236import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700237import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800238import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900239import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000240import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600241import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900242import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700243import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700244import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800245
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800246import androidx.annotation.RequiresApi;
247
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900248import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400249import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400250import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700251import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900252import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800253import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900254import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800255import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000256import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900257import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900258import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900259import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100260import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900261import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
262import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900263import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800264import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800265import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100266import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000267import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800268import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
269import com.android.networkstack.apishim.ConstantsShim;
270import com.android.networkstack.apishim.common.BroadcastOptionsShim;
271import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Chalard Jean7284daa2019-05-30 14:58:29 +0900272import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000273import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900274import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800275import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800276import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900277import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900278import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500279import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700280import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900281import com.android.server.connectivity.FullScore;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000282import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100283import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700284import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900285import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700286import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600287import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900288import com.android.server.connectivity.NetworkNotificationManager;
289import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900290import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900291import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900292import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700293import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900294import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900295import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700296import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800297import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000298import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800299import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600300
Josh Gao461a1222020-06-16 15:58:11 -0700301import libcore.io.IoUtils;
302
The Android Open Source Project28527d22009-03-03 19:31:44 -0800303import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100304import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800305import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900306import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700307import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700308import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900309import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700310import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700311import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700312import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700313import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800314import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900315import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800316import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700317import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700318import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700319import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700320import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900321import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700322import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900323import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600324import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900325import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600326import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900327import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800328
329/**
330 * @hide
331 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800332public class ConnectivityService extends IConnectivityManager.Stub
333 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900334 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800335
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900336 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900337 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900338 private static final String NETWORK_ARG = "networks";
339 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800340 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900341
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900342 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900343 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
344 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800345
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900346 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700347
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100348 /**
349 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
350 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800351 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100352 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
353 * (preferably via runtime resource overlays).
354 */
355 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
356 "http://connectivitycheck.gstatic.com/generate_204";
357
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700358 // TODO: create better separation between radio types and network types
359
Robert Greenwalt2034b912009-08-12 16:08:25 -0700360 // how long to wait before switching back to a radio's default network
361 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
362 // system property that can override the above value
363 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
364 "android.telephony.apn-restore";
365
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900366 // How long to wait before putting up a "This network doesn't have an Internet connection,
367 // connect anyway?" dialog after the user selects a network that doesn't validate.
368 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
369
Chalard Jean5fb43c72022-09-08 19:03:14 +0900370 // How long to wait before considering that a network is bad in the absence of any form
371 // of connectivity (valid, partial, captive portal). If none has been detected after this
372 // delay, the stack considers this network bad, which may affect how it's handled in ranking
373 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900374 // Timeout in case the "actively prefer bad wifi" feature is on
375 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
376 // Timeout in case the "actively prefer bad wifi" feature is off
377 private static final int DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900378
junyulai0ac374f2020-12-14 18:41:52 +0800379 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900380 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
381 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800382 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700383
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800384 // Delimiter used when creating the broadcast delivery group for sending
385 // CONNECTIVITY_ACTION broadcast.
386 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
387
he_won.hwang881307a2022-03-15 21:23:52 +0900388 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900389 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900390
Daniel Brightf9e945b2020-06-15 16:10:01 -0700391 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900392 @VisibleForTesting
393 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700394
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900395 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700396 @VisibleForTesting
397 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900398
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900399 @VisibleForTesting
400 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800401 @VisibleForTesting
402 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900403 // True if the cell radio of the device is capable of time-sharing.
404 @VisibleForTesting
405 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900406
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800407 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800408 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800409 private final int mReleasePendingIntentDelayMs;
410
Chalard Jean46bfbf02022-02-02 00:56:25 +0900411 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900412
Motomu Utsumif360aa62023-01-30 17:52:20 +0900413 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700414
Chalard Jean9473c982021-07-29 20:03:04 +0900415 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800416 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700417 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800418 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700419
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900420 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700421
junyulaif2c67e42018-08-07 19:50:45 +0800422 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000423 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
424 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800425 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900426 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800427
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900428 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900429 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000430 // The Context is created for UserHandle.ALL.
431 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900432 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900433 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700434 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700435 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800436
Chenbo Feng15416292018-11-08 17:36:21 -0800437 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800438 protected IDnsResolver mDnsResolver;
439 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800440 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700441 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900442 private final NetworkStatsManager mStatsManager;
443 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800444 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700445
Benedict Wong493e04b2018-11-09 14:45:34 -0800446 /**
447 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
448 * instances.
449 */
450 @GuardedBy("mTNSLock")
451 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800452 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800453
454 private final Object mTNSLock = new Object();
455
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700456 private String mCurrentTcpBufferSizes;
457
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900458 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800459 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900460
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500461 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400462 // Tear down networks that have no chance (e.g. even if validated) of becoming
463 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500464 // all networks have been rematched against all NetworkRequests.
465 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400466 // Don't reap networks. This should be passed when some networks have not yet been
467 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500468 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900469 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500470
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900471 private enum UnneededFor {
472 LINGER, // Determine whether this network is unneeded and should be lingered.
473 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
474 }
475
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700476 /**
paulhuaa0743d2021-05-26 21:56:03 +0800477 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800478 * should have priority. The order is passed to netd which will use it together
479 * with UID ranges to generate the corresponding IP rule. This serves to
480 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800481 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800482 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000483 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800484 *
paulhu48291862021-07-14 14:53:57 +0800485 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
486 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800487 */
paulhu48291862021-07-14 14:53:57 +0800488 // Used when sending to netd to code for "no order".
489 static final int PREFERENCE_ORDER_NONE = 0;
490 // Order for requests that don't code for a per-app preference. As it is
491 // out of the valid range, the corresponding order should be
492 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800493 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800494 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800495 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800496 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
497 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800498 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800499 static final int PREFERENCE_ORDER_OEM = 10;
500 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800501 // See {@link #setProfileNetworkPreference}.
502 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800503 static final int PREFERENCE_ORDER_PROFILE = 20;
504 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800505 // better scores are connected.
506 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800507 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800508 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900509 // Preference order that signifies the network shouldn't be set as a default network for
510 // the UIDs, only give them access to it. TODO : replace this with a boolean
511 // in NativeUidRangeConfig
512 @VisibleForTesting
513 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
514 // Bound for the lowest valid preference order.
515 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800516
517 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700518 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700519 * from one net to another. Clear happens when we get a new
520 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
521 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700522 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700523 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700524
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700525 /**
526 * used internally to reload global proxy settings
527 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700528 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700529
Robert Greenwalt34848c02011-03-25 13:09:25 -0700530 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400531 * PAC manager has received new port.
532 */
533 private static final int EVENT_PROXY_HAS_CHANGED = 16;
534
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700535 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900536 * used internally when registering NetworkProviders
537 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700538 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900539 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700540
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700541 /**
542 * used internally when registering NetworkAgents
543 * obj = Messenger
544 */
545 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
546
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700547 /**
548 * used to add a network request
549 * includes a NetworkRequestInfo
550 */
551 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
552
553 /**
554 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900555 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700556 * cancel it.
557 * includes a NetworkRequestInfo
558 */
559 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
560
561 /**
562 * used to add a network listener - no request
563 * includes a NetworkRequestInfo
564 */
565 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
566
567 /**
568 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400569 * arg1 = UID of caller
570 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700571 */
572 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
573
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700574 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900575 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700576 * obj = Messenger
577 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900578 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700579
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700580 /**
581 * used internally to expire a wakelock when transitioning
582 * from one net to another. Expire happens when we fail to find
583 * a new network (typically after 1 minute) -
584 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
585 * a replacement network.
586 */
587 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
588
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700589 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800590 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400591 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800592 */
593 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
594
595 /**
596 * used to remove a pending intent and its associated network request.
597 * arg1 = UID of caller
598 * obj = PendingIntent
599 */
600 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
601
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900602 /**
603 * used to specify whether a network should be used even if unvalidated.
604 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
605 * arg2 = whether to remember this choice in the future (1 or 0)
606 * obj = network
607 */
608 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
609
610 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700611 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900612 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700613 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900614
Paul Jensenc8873fc2015-06-17 14:15:39 -0400615 /**
616 * used to add a network listener with a pending intent
617 * obj = NetworkRequestInfo
618 */
619 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
620
Hugo Benichid6b510a2017-04-06 17:22:18 +0900621 /**
622 * used to specify whether a network should not be penalized when it becomes unvalidated.
623 */
624 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
625
626 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700627 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900628 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700629 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900630
Erik Kline31b4a9e2018-01-11 21:07:29 +0900631 // Handle changes in Private DNS settings.
632 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
633
dalyk1720e542018-03-05 12:42:22 -0500634 // Handle private DNS validation status updates.
635 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
636
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900637 /**
638 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
639 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800640 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
641 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
642 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900643 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900644 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900645
646 /**
647 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
648 * config was resolved.
649 * obj = PrivateDnsConfig
650 * arg2 = netid
651 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900652 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900653
654 /**
655 * Request ConnectivityService display provisioning notification.
656 * arg1 = Whether to make the notification visible.
657 * arg2 = NetID.
658 * obj = Intent to be launched when notification selected by user, null if !arg1.
659 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900660 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900661
662 /**
lucaslin2240ef62019-03-12 13:08:03 +0800663 * Used to specify whether a network should be used even if connectivity is partial.
664 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
665 * false)
666 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
667 * obj = network
668 */
lucaslin444d43a2020-02-20 16:56:59 +0800669 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800670
671 /**
lucasline117e2e2019-10-22 18:27:33 +0800672 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
673 * Both of the arguments are bitmasks, and the value of bits come from
674 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900675 * arg1 = unused
676 * arg2 = netId
677 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800678 */
lucaslin444d43a2020-02-20 16:56:59 +0800679 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800680
681 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900682 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
683 * arg1 = unused
684 * arg2 = netId
685 * obj = captive portal data
686 */
lucaslin444d43a2020-02-20 16:56:59 +0800687 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900688
689 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900690 * Used by setRequireVpnForUids.
691 * arg1 = whether the specified UID ranges are required to use a VPN.
692 * obj = Array of UidRange objects.
693 */
694 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
695
696 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900697 * Used internally when setting the default networks for OemNetworkPreferences.
698 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800699 */
700 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
701
702 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800703 * Used to indicate the system default network becomes active.
704 */
705 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
706
707 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900708 * Used internally when setting a network preference for a user profile.
709 * obj = Pair<ProfileNetworkPreference, Listener>
710 */
711 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
712
713 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000714 * Event to specify that reasons for why an uid is blocked changed.
715 * arg1 = uid
716 * arg2 = blockedReasons
717 */
718 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
719
720 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900721 * Event to register a new network offer
722 * obj = NetworkOffer
723 */
724 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
725
726 /**
727 * Event to unregister an existing network offer
728 * obj = INetworkOfferCallback
729 */
730 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
731
732 /**
paulhu51f77dc2021-06-07 02:34:20 +0000733 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
734 */
735 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
736
737 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800738 * Event to set temporary allow bad wifi within a limited time to override
739 * {@code config_networkAvoidBadWifi}.
740 */
741 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
742
743 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100744 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
745 */
746 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
747
748 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900749 * The initial evaluation period is over for this network.
750 *
751 * If no form of connectivity has been found on this network (valid, partial, captive portal)
752 * then the stack will now consider it to have been determined bad.
753 */
754 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
755
756 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000757 * Used internally when the user does not want the network from captive portal app.
758 * obj = Network
759 */
760 private static final int EVENT_USER_DOES_NOT_WANT = 58;
761
762 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000763 * Event to set VPN as preferred network for specific apps.
764 * obj = VpnNetworkPreferenceInfo
765 */
766 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
767
768 /**
chiachangwange0192a72023-02-06 13:25:01 +0000769 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
770 */
771 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
772
773 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900774 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
775 * should be shown.
776 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900777 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900778
779 /**
780 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
781 * should be hidden.
782 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900783 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900784
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800785 /**
786 * The maximum alive time to allow bad wifi configuration for testing.
787 */
788 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
789
Patrick Rohr2857ac42022-01-21 14:58:16 +0100790 /**
chiachangwange0192a72023-02-06 13:25:01 +0000791 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
792 * testing.
793 */
794 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
795
796 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100797 * The priority of the tc police rate limiter -- smaller value is higher priority.
798 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
799 */
800 private static final short TC_PRIO_POLICE = 1;
801
802 /**
803 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
804 */
805 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700806 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100807
Hugo Benichi47011212017-03-30 10:46:05 +0900808 private static String eventName(int what) {
809 return sMagicDecoderRing.get(what, Integer.toString(what));
810 }
811
paulhua10d8212020-11-10 15:32:56 +0800812 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900813 final DnsResolverServiceManager dsm = context.getSystemService(
814 DnsResolverServiceManager.class);
815 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800816 }
817
Cody Kesting73708bf2019-12-18 10:57:50 -0800818 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900819 @VisibleForTesting
820 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700821 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700822 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700823 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700824 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800825 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
826 @VisibleForTesting
827 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
828
Erik Kline32120082017-12-13 19:40:49 +0900829 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900830 @VisibleForTesting
831 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700832
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400833 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800834 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400835
Chalard Jean46bfbf02022-02-02 00:56:25 +0900836 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800837 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700838
Chalard Jean5d70ba42018-06-07 16:44:04 +0900839 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
840 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000841 @VisibleForTesting
842 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400843
Erik Kline05f2b402015-04-30 12:58:40 +0900844 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700845
Chalard Jean46bfbf02022-02-02 00:56:25 +0900846 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400847
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700848 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900849 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700850
Valentin Iftime9fa35092019-09-24 13:32:13 +0200851 private Set<String> mWolSupportedInterfaces;
852
Roshan Pius08c94fb2020-01-16 12:17:17 -0800853 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800854 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800855 private final AppOpsManager mAppOpsManager;
856
857 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400858
chiachangwang3d60bac2023-01-17 14:38:08 +0000859 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900860 private final QosCallbackTracker mQosCallbackTracker;
861 private final NetworkNotificationManager mNotifier;
862 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900863
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700864 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800865 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700866
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900867 // Sequence number for NetworkProvider IDs.
868 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
869 NetworkProvider.FIRST_PROVIDER_ID);
870
Erik Klineedf878b2015-07-09 18:24:03 +0900871 // NetworkRequest activity String log entries.
872 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
873 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
874
Hugo Benichid159fdd2016-07-11 11:05:12 +0900875 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900876 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900877 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
878
Hugo Benichi47011212017-03-30 10:46:05 +0900879 private static final int MAX_WAKELOCK_LOGS = 20;
880 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900881 private int mTotalWakelockAcquisitions = 0;
882 private int mTotalWakelockReleases = 0;
883 private long mTotalWakelockDurationMs = 0;
884 private long mMaxWakelockDurationMs = 0;
885 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900886
Hugo Benichi208c0102016-07-28 17:53:06 +0900887 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900888
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700889 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900890 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700891
Erik Kline95ecfee2016-10-02 18:02:14 +0900892 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900893 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900894
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900895 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800896 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
897 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800898
Patrick Rohr2857ac42022-01-21 14:58:16 +0100899 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
900 // configured via {@link
901 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
902 // Only the handler thread is allowed to access this field.
903 private long mIngressRateLimit = -1;
904
Robert Greenwalt802c1102014-06-02 15:32:02 -0700905 /**
906 * Implements support for the legacy "one network per network type" model.
907 *
908 * We used to have a static array of NetworkStateTrackers, one for each
909 * network type, but that doesn't work any more now that we can have,
910 * for example, more that one wifi network. This class stores all the
911 * NetworkAgentInfo objects that support a given type, but the legacy
912 * API will only see the first one.
913 *
914 * It serves two main purposes:
915 *
916 * 1. Provide information about "the network for a given type" (since this
917 * API only supports one).
918 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
919 * the first network for a given type changes, or if the default network
920 * changes.
921 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900922 @VisibleForTesting
923 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900924
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900925 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900926 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900927
Robert Greenwalt802c1102014-06-02 15:32:02 -0700928 /**
929 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
930 * Each list holds references to all NetworkAgentInfos that are used to
931 * satisfy requests for that network type.
932 *
933 * This array is built out at startup such that an unsupported network
934 * doesn't get an ArrayList instance, making this a tristate:
935 * unsupported, supported but not active and active.
936 *
937 * The actual lists are populated when we scan the network types that
938 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900939 *
940 * Threading model:
941 * - addSupportedType() is only called in the constructor
942 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
943 * They are therefore not thread-safe with respect to each other.
944 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
945 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900946 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900947 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700948 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900949 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900950 @NonNull
951 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700952
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900953 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
954 // an entry have no timer (equivalent to -1). Lazily loaded.
955 @NonNull
956 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
957
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900958 LegacyTypeTracker(@NonNull ConnectivityService service) {
959 mService = service;
960 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700961 }
962
Chiachang Wang3bc52762021-11-25 14:17:57 +0800963 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
964 // addressed.
965 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900966 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
967 final PackageManager pm = ctx.getPackageManager();
968 if (pm.hasSystemFeature(FEATURE_WIFI)) {
969 addSupportedType(TYPE_WIFI);
970 }
971 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
972 addSupportedType(TYPE_WIFI_P2P);
973 }
974 if (tm.isDataCapable()) {
975 // Telephony does not have granular support for these types: they are either all
976 // supported, or none is supported
977 addSupportedType(TYPE_MOBILE);
978 addSupportedType(TYPE_MOBILE_MMS);
979 addSupportedType(TYPE_MOBILE_SUPL);
980 addSupportedType(TYPE_MOBILE_DUN);
981 addSupportedType(TYPE_MOBILE_HIPRI);
982 addSupportedType(TYPE_MOBILE_FOTA);
983 addSupportedType(TYPE_MOBILE_IMS);
984 addSupportedType(TYPE_MOBILE_CBS);
985 addSupportedType(TYPE_MOBILE_IA);
986 addSupportedType(TYPE_MOBILE_EMERGENCY);
987 }
988 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
989 addSupportedType(TYPE_BLUETOOTH);
990 }
991 if (pm.hasSystemFeature(FEATURE_WATCH)) {
992 // TYPE_PROXY is only used on Wear
993 addSupportedType(TYPE_PROXY);
994 }
995 // Ethernet is often not specified in the configs, although many devices can use it via
996 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +0000997 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900998 addSupportedType(TYPE_ETHERNET);
999 }
1000
1001 // Always add TYPE_VPN as a supported type
1002 addSupportedType(TYPE_VPN);
1003 }
1004
1005 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001006 if (mTypeLists[type] != null) {
1007 throw new IllegalStateException(
1008 "legacy list for type " + type + "already initialized");
1009 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001010 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001011 }
1012
Robert Greenwalt802c1102014-06-02 15:32:02 -07001013 public boolean isTypeSupported(int type) {
1014 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1015 }
1016
1017 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001018 synchronized (mTypeLists) {
1019 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1020 return mTypeLists[type].get(0);
1021 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001022 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001023 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001024 }
1025
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001026 public int getRestoreTimerForType(int type) {
1027 synchronized (mTypeLists) {
1028 if (mRestoreTimers == null) {
1029 mRestoreTimers = loadRestoreTimers();
1030 }
1031 return mRestoreTimers.getOrDefault(type, -1);
1032 }
1033 }
1034
1035 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1036 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001037 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001038 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1039 for (final String config : configs) {
1040 final String[] splits = TextUtils.split(config, ",");
1041 if (splits.length != 2) {
1042 logwtf("Invalid restore timer token count: " + config);
1043 continue;
1044 }
1045 try {
1046 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1047 } catch (NumberFormatException e) {
1048 logwtf("Invalid restore timer number format: " + config, e);
1049 }
1050 }
1051 return ret;
1052 }
1053
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001054 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001055 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001056 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001057 log("Sending " + state
1058 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001059 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001060 }
1061 }
1062
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001063 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1064 // network type, to preserve previous behaviour.
1065 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1066 if (vpnNai != mService.getLegacyLockdownNai()) return;
1067
1068 if (vpnNai.declaredUnderlyingNetworks == null
1069 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1070 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1071 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1072 return;
1073 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001074 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001075 vpnNai.declaredUnderlyingNetworks[0]);
1076 if (underlyingNai == null) return;
1077
1078 final int type = underlyingNai.networkInfo.getType();
1079 final DetailedState state = DetailedState.CONNECTED;
1080 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1081 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1082 }
1083
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001084 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001085 public void add(int type, NetworkAgentInfo nai) {
1086 if (!isTypeSupported(type)) {
1087 return; // Invalid network type.
1088 }
1089 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1090
1091 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1092 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001093 return;
1094 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001095 synchronized (mTypeLists) {
1096 list.add(nai);
1097 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001098
Chalard Jean5b409c72021-02-04 13:12:59 +09001099 // Send a broadcast if this is the first network of its type or if it's the default.
1100 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001101
1102 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1103 // to preserve previous behaviour.
1104 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001105 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001106 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1107 mService.sendLegacyNetworkBroadcast(nai, state, type);
1108 }
1109
1110 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1111 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001112 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001113 }
1114
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001115 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001116 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001117 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1118 if (list == null || list.isEmpty()) {
1119 return;
1120 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001121 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001122
Hugo Benichi389633f2016-06-21 09:48:07 +09001123 synchronized (mTypeLists) {
1124 if (!list.remove(nai)) {
1125 return;
1126 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001127 }
1128
Lorenzo Colitti49767722015-05-01 00:30:10 +09001129 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001130 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1131 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001132 }
1133
1134 if (!list.isEmpty() && wasFirstNetwork) {
1135 if (DBG) log("Other network available for type " + type +
1136 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001137 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001138 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001139 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001140 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001141 }
1142 }
1143
1144 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001145 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1146 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001147 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001148 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001149 }
1150 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001151
Chalard Jean46bfbf02022-02-02 00:56:25 +09001152 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001153 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001154 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001155 final DetailedState state = nai.networkInfo.getDetailedState();
1156 for (int type = 0; type < mTypeLists.length; type++) {
1157 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001158 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001159 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001160 if (isFirst || contains && isDefault) {
1161 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001162 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001163 }
1164 }
1165 }
1166
Robert Greenwalt94e22142014-07-30 16:31:24 -07001167 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001168 pw.println("mLegacyTypeTracker:");
1169 pw.increaseIndent();
1170 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001171 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001172 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001173 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001174 pw.println();
1175 pw.println("Current state:");
1176 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001177 synchronized (mTypeLists) {
1178 for (int type = 0; type < mTypeLists.length; type++) {
1179 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1180 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001181 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001182 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001183 }
1184 }
1185 pw.decreaseIndent();
1186 pw.decreaseIndent();
1187 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001188 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001189 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001190 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001191
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001192 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001193 /**
1194 * Helper class which parses out priority arguments and dumps sections according to their
1195 * priority. If priority arguments are omitted, function calls the legacy dump command.
1196 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001197 private class LocalPriorityDump {
1198 private static final String PRIORITY_ARG = "--dump-priority";
1199 private static final String PRIORITY_ARG_HIGH = "HIGH";
1200 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1201
1202 LocalPriorityDump() {}
1203
1204 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1205 doDump(fd, pw, new String[] {DIAG_ARG});
1206 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001207 }
1208
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001209 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1210 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001211 }
1212
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001213 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1214 if (args == null) {
1215 dumpNormal(fd, pw, args);
1216 return;
1217 }
1218
1219 String priority = null;
1220 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1221 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1222 argIndex++;
1223 priority = args[argIndex];
1224 }
1225 }
1226
1227 if (PRIORITY_ARG_HIGH.equals(priority)) {
1228 dumpHigh(fd, pw);
1229 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1230 dumpNormal(fd, pw, args);
1231 } else {
1232 // ConnectivityService publishes binder service using publishBinderService() with
1233 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001234 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1235 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001236 // TODO: Integrate into signal dump.
1237 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001238 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001239 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001240 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001241
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001242 /**
1243 * Dependencies of ConnectivityService, for injection in tests.
1244 */
1245 @VisibleForTesting
1246 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001247 public int getCallingUid() {
1248 return Binder.getCallingUid();
1249 }
1250
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001251 /**
1252 * Get system properties to use in ConnectivityService.
1253 */
1254 public MockableSystemProperties getSystemProperties() {
1255 return new MockableSystemProperties();
1256 }
1257
1258 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001259 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1260 */
1261 public ConnectivityResources getResources(@NonNull Context ctx) {
1262 return new ConnectivityResources(ctx);
1263 }
1264
1265 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001266 * Create a HandlerThread to use in ConnectivityService.
1267 */
1268 public HandlerThread makeHandlerThread() {
1269 return new HandlerThread("ConnectivityServiceThread");
1270 }
1271
1272 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001273 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001274 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001275 public NetworkStackClientBase getNetworkStack() {
1276 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001277 }
1278
1279 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001280 * @see ProxyTracker
1281 */
1282 public ProxyTracker makeProxyTracker(@NonNull Context context,
1283 @NonNull Handler connServiceHandler) {
1284 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1285 }
1286
1287 /**
1288 * @see NetIdManager
1289 */
1290 public NetIdManager makeNetIdManager() {
1291 return new NetIdManager();
1292 }
1293
1294 /**
1295 * @see NetworkUtils#queryUserAccess(int, int)
1296 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001297 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1298 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001299 }
1300
1301 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001302 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1303 * requires CAP_NET_ADMIN, which the unit tests do not have.
1304 */
1305 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1306 InetSocketAddress remote) {
1307 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1308 }
1309
1310 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001311 * @see MultinetworkPolicyTracker
1312 */
1313 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1314 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1315 return new MultinetworkPolicyTracker(c, h, r);
1316 }
1317
Aaron Huang330a4c02020-10-27 03:36:19 +08001318 /**
1319 * @see BatteryStatsManager
1320 */
1321 public void reportNetworkInterfaceForTransports(Context context, String iface,
1322 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001323 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001324 context.getSystemService(BatteryStatsManager.class);
1325 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1326 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001327
1328 public boolean getCellular464XlatEnabled() {
1329 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1330 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001331
1332 /**
1333 * @see PendingIntent#intentFilterEquals
1334 */
1335 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1336 return a.intentFilterEquals(b);
1337 }
1338
1339 /**
1340 * @see LocationPermissionChecker
1341 */
1342 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1343 return new LocationPermissionChecker(context);
1344 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001345
1346 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001347 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001348 *
1349 * This method returns null in versions before T, where carrier privilege
1350 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001351 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001352 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001353 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1354 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1355 if (SdkLevel.isAtLeastT()) {
1356 return new CarrierPrivilegeAuthenticator(context, tm);
1357 } else {
1358 return null;
1359 }
1360 }
1361
1362 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001363 * @see DeviceConfigUtils#isFeatureEnabled
1364 */
1365 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1366 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1367 TETHERING_MODULE_NAME, defaultEnabled);
1368 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001369
1370 /**
1371 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001372 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001373 * @return BpfNetMaps implementation.
1374 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001375 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1376 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001377 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001378
1379 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001380 * @see ClatCoordinator
1381 */
1382 public ClatCoordinator getClatCoordinator(INetd netd) {
1383 return new ClatCoordinator(
1384 new ClatCoordinator.Dependencies() {
1385 @NonNull
1386 public INetd getNetd() {
1387 return netd;
1388 }
1389 });
1390 }
1391
1392 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001393 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1394 */
1395 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1396 final InterfaceParams params = InterfaceParams.getByName(iface);
1397 if (params == null) {
1398 // the interface might have disappeared.
1399 logw("Failed to get interface params for interface " + iface);
1400 return;
1401 }
1402 try {
1403 // converting rateInBytesPerSecond from long to int is safe here because the
1404 // setting's range is limited to INT_MAX.
1405 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001406 Log.i(TAG,
1407 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001408 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1409 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1410 } catch (IOException e) {
1411 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1412 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1413 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1414 + ") failure: ", e);
1415 }
1416 }
1417
1418 /**
1419 * Wraps {@link TcUtils#tcFilterDelDev}
1420 */
1421 public void disableIngressRateLimit(String iface) {
1422 final InterfaceParams params = InterfaceParams.getByName(iface);
1423 if (params == null) {
1424 // the interface might have disappeared.
1425 logw("Failed to get interface params for interface " + iface);
1426 return;
1427 }
1428 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001429 Log.i(TAG,
1430 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001431 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1432 } catch (IOException e) {
1433 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1434 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1435 }
1436 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001437
1438 /**
1439 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1440 */
1441 // TODO: when available in all active branches:
1442 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1443 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1444 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1445 return BroadcastOptionsShimImpl.newInstance(options);
1446 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001447 }
1448
junyulaie7c7d2a2021-01-26 15:29:15 +08001449 public ConnectivityService(Context context) {
1450 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001451 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1452 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001453 }
1454
1455 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001456 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1457 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001458 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001459
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001460 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001461 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001462 mSystemProperties = mDeps.getSystemProperties();
1463 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001464 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001465 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001466 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1467 // Pass limit - 1 to maintain backward compatibility.
1468 // TODO: Remove the workaround.
1469 mNetworkRequestCounter =
1470 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1471 mSystemNetworkRequestCounter =
1472 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001473
Hugo Benichi208c0102016-07-28 17:53:06 +09001474 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001475 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1476 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001477 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001478 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001479 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001480 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1481 mDefaultNetworkRequests.add(mDefaultRequest);
1482 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001483
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001484 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001485 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001486
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001487 // The default WiFi request is a background request so that apps using WiFi are
1488 // migrated to a better network (typically ethernet) when one comes up, instead
1489 // of staying on WiFi forever.
1490 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1491 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1492
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001493 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1494 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1495 NetworkRequest.Type.BACKGROUND_REQUEST);
1496
Chalard Jean0702f982021-09-16 21:50:07 +09001497 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1498 // TODO: Consider making the timer customizable.
1499 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1500 mCellularRadioTimesharingCapable =
1501 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1502
Paul Hu51f816b2022-08-11 14:43:47 +00001503 mNetd = netd;
1504 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001505 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001506 mPermissionMonitor =
1507 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001508 mHandlerThread.start();
1509 mHandler = new InternalHandler(mHandlerThread.getLooper());
1510 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001511 mConnectivityDiagnosticsHandler =
1512 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001513
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001514 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001515 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001516
junyulaie7c7d2a2021-01-26 15:29:15 +08001517 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001518 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001519 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001520 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001521
Wink Saville32506bc2013-06-29 21:10:57 -07001522 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001523 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001524 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001525 mCarrierPrivilegeAuthenticator =
1526 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001527
Sudheer Shanka9967d462021-03-18 19:09:25 +00001528 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001529 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1530 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001531 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001532
1533 final PowerManager powerManager = (PowerManager) context.getSystemService(
1534 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001535 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001536 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001537
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001538 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1539 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001540 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001541 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001542 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001543 mProtectedNetworks.add(p);
1544 } else {
1545 if (DBG) loge("Ignoring protectedNetwork " + p);
1546 }
1547 }
1548
soma, kawata29444ae2019-05-23 09:30:40 +09001549 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1550
James Mattis02220e22021-03-13 19:27:21 -08001551 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001552 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001553 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001554 final IntentFilter userIntentFilter = new IntentFilter();
1555 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1556 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1557 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1558 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001559
James Mattis02220e22021-03-13 19:27:21 -08001560 // Listen to package add/removes for netd
1561 final IntentFilter packageIntentFilter = new IntentFilter();
1562 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1563 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1564 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1565 packageIntentFilter.addDataScheme("package");
1566 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001567 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001568
lucaslind5c2d072021-02-20 18:59:47 +08001569 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001570
Chalard Jean46bfbf02022-02-02 00:56:25 +09001571 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001572 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001573 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001574 } catch (RemoteException | ServiceSpecificException e) {
1575 loge("Error registering event listener :" + e);
1576 }
1577
Erik Kline05f2b402015-04-30 12:58:40 +09001578 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1579 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001580
chiachangwang3d60bac2023-01-17 14:38:08 +00001581 mKeepaliveTracker = new AutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001582 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001583 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001584
1585 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001586 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001587 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1588 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001589 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001590 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1591 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001592
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001593 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001594 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001595 mNetworkRanker =
1596 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1597
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001598 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001599
Chiachang Wangc1215d32020-10-20 15:38:58 +08001600 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001601 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001602
Chalard Jean28018572020-12-21 18:36:52 +09001603 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1604 // request that doesn't allow fallback to the default network. It should never be visible
1605 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1606 // arguments like the handler or the DnsResolver.
1607 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001608 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001609 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001610 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001611 new LinkProperties(), new NetworkCapabilities(),
1612 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001613 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1614 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001615
1616 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001617 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1618 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1619 // Even if it could, running on S would at least require mocking out the BPF map,
1620 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1621 // the bpf syscall. http://aosp/1907693
1622 if (SdkLevel.isAtLeastT()) {
1623 mDscpPolicyTracker = new DscpPolicyTracker();
1624 }
Tyler Wear72388212021-09-09 14:49:02 -07001625 } catch (ErrnoException e) {
1626 loge("Unable to create DscpPolicyTracker");
1627 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001628
1629 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1630 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001631
1632 if (SdkLevel.isAtLeastT()) {
1633 mCdmps = new CompanionDeviceManagerProxyService(context);
1634 } else {
1635 mCdmps = null;
1636 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001637 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001638
Xiao Ma0a171c02022-01-23 16:14:51 +00001639 /**
1640 * Check whether or not the device supports Ethernet transport.
1641 */
1642 public static boolean deviceSupportsEthernet(final Context context) {
1643 final PackageManager pm = context.getPackageManager();
1644 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1645 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1646 }
1647
Chalard Jean46adcf32018-04-18 20:18:38 +09001648 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001649 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1650 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001651 }
1652
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001653 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1654 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001655 final NetworkCapabilities netCap = new NetworkCapabilities();
1656 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001657 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001658 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001659 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001660 return netCap;
1661 }
1662
James Mattis45d81842021-01-10 14:24:24 -08001663 private NetworkRequest createDefaultRequest() {
1664 return createDefaultInternetRequestForTransport(
1665 TYPE_NONE, NetworkRequest.Type.REQUEST);
1666 }
1667
lucaslin3ba7cc22022-12-19 02:35:33 +00001668 private NetworkRequest createVpnRequest() {
1669 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1670 .withoutDefaultCapabilities()
1671 .addTransportType(TRANSPORT_VPN)
1672 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1673 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1674 .build();
1675 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1676 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1677 }
1678
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001679 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001680 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001681 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001682 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001683 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001684 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001685 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001686 netCap.addTransportType(transportType);
1687 }
James Mattis45d81842021-01-10 14:24:24 -08001688 return createNetworkRequest(type, netCap);
1689 }
1690
1691 private NetworkRequest createNetworkRequest(
1692 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001693 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001694 }
1695
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001696 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1697 NetworkRequest.Type type) {
1698 final NetworkCapabilities netCap = new NetworkCapabilities();
1699 netCap.clearAll();
1700 netCap.addCapability(capability);
1701 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1702 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1703 }
1704
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001705 // Used only for testing.
1706 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001707 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001708 // changing ContentResolver to make registerContentObserver non-final).
1709 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1710 // by subclassing SettingsObserver.
1711 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001712 void updateAlwaysOnNetworks() {
1713 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001714 }
1715
Erik Kline9a62f012018-03-21 07:18:33 -07001716 // See FakeSettingsProvider comment above.
1717 @VisibleForTesting
1718 void updatePrivateDnsSettings() {
1719 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1720 }
1721
paulhu51f77dc2021-06-07 02:34:20 +00001722 @VisibleForTesting
1723 void updateMobileDataPreferredUids() {
1724 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1725 }
1726
Patrick Rohr2857ac42022-01-21 14:58:16 +01001727 @VisibleForTesting
1728 void updateIngressRateLimit() {
1729 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1730 }
1731
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001732 private void handleAlwaysOnNetworkRequest(
1733 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001734 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001735 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001736 handleAlwaysOnNetworkRequest(networkRequest, enable);
1737 }
1738
1739 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001740 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001741 if (enable == isEnabled) {
1742 return; // Nothing to do.
1743 }
1744
1745 if (enable) {
1746 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001747 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001748 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001749 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001750 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001751 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1752 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001753 }
1754 }
1755
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001756 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001757 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1758 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1759 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1760 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001761 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1762 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001763 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001764 }
1765
paulhu51f77dc2021-06-07 02:34:20 +00001766 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001767 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001768 private void registerSettingsCallbacks() {
1769 // Watch for global HTTP proxy changes.
1770 mSettingsObserver.observe(
1771 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1772 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1773
Chalard Jean46bfbf02022-02-02 00:56:25 +09001774 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001775 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001776 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001777 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1778
Chalard Jean46bfbf02022-02-02 00:56:25 +09001779 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001780 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001781 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001782 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001783
1784 // Watch for mobile data preferred uids changes.
1785 mSettingsObserver.observe(
1786 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1787 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001788
1789 // Watch for ingress rate limit changes.
1790 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001791 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001792 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1793 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001794 }
1795
Erik Kline31b4a9e2018-01-11 21:07:29 +09001796 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001797 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1798 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001799 }
1800 }
1801
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001802 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001803 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1804 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001805 return mNextNetworkRequestId++;
1806 }
1807
junyulai74f9a8b2018-06-13 15:00:37 +08001808 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001809 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001810 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001811 if (network == null) {
1812 return null;
1813 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001814 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001815 }
1816
1817 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001818 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001819 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001820 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001821 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001822
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001823 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001824 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001825 private NetworkAgentInfo getVpnForUid(int uid) {
1826 synchronized (mNetworkForNetId) {
1827 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1828 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001829 if (nai.isVPN() && nai.everConnected()
1830 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001831 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001832 }
1833 }
1834 }
1835 return null;
1836 }
1837
Chalard Jean46bfbf02022-02-02 00:56:25 +09001838 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001839 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001840 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001841 final NetworkAgentInfo nai = getVpnForUid(uid);
1842 if (nai != null) return nai.declaredUnderlyingNetworks;
1843 return null;
1844 }
1845
Lorenzo Colittia7574052021-01-19 01:33:05 +09001846 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001847 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001848
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001849 final Network[] networks = getVpnUnderlyingNetworks(uid);
1850 if (networks != null) {
1851 // getUnderlyingNetworks() returns:
1852 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1853 // empty array => the VPN explicitly said "no default network".
1854 // non-empty array => the VPN specified one or more default networks; we use the
1855 // first one.
1856 if (networks.length > 0) {
1857 nai = getNetworkAgentInfoForNetwork(networks[0]);
1858 } else {
1859 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001860 }
1861 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001862 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001863 }
1864
1865 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001866 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001867 */
paulhu7aeba372020-12-30 00:42:19 +08001868 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1869 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001870 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001871 if (ignoreBlocked) {
1872 return false;
1873 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001874 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001875 final long ident = Binder.clearCallingIdentity();
1876 try {
1877 final boolean metered = nc == null ? true : nc.isMetered();
1878 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1879 } finally {
1880 Binder.restoreCallingIdentity(ident);
1881 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001882 }
1883
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001884 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001885 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1886 return;
1887 }
Hugo Benichi47011212017-03-30 10:46:05 +09001888 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001889 synchronized (mBlockedAppUids) {
1890 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001891 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001892 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001893 blocked = false;
1894 } else {
1895 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001896 }
1897 }
Hugo Benichi47011212017-03-30 10:46:05 +09001898 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1899 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1900 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001901 }
1902
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001903 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001904 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1905 return;
1906 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001907 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001908 final int requestId = nri.getActiveRequest() != null
1909 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001910 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001911 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001912 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001913 }
1914
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001915 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001916 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001917 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001918 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001919 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001920 @NonNull
1921 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1922 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001923 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1924 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1925 // but only exists if an app asks about them or requests them. Ensure the requesting app
1926 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001927 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001928 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1929 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1930 null /* extraInfo */);
1931 }
1932 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001933 return filtered;
1934 }
1935
1936 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1937 boolean ignoreBlocked) {
1938 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1939 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001940 }
1941
1942 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001943 * Return NetworkInfo for the active (i.e., connected) network interface.
1944 * It is assumed that at most one network is active at a time. If more
1945 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001946 * @return the info for the active network, or {@code null} if none is
1947 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001948 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001949 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001950 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001951 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001952 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001953 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001954 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1955 if (nai == null) return null;
1956 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1957 maybeLogBlockedNetworkInfo(networkInfo, uid);
1958 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001959 }
1960
Paul Jensen1f567382015-02-13 14:18:39 -05001961 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001962 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001963 public Network getActiveNetwork() {
1964 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001965 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001966 }
1967
1968 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001969 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001970 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001971 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001972 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001973 }
1974
Chalard Jean46bfbf02022-02-02 00:56:25 +09001975 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001976 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001977 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1978 if (vpnNai != null) {
1979 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1980 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1981 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001982 }
Paul Jensen1f567382015-02-13 14:18:39 -05001983 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001984
James Mattis2516da32021-01-31 17:06:19 -08001985 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001986 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1987 ignoreBlocked)) {
1988 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001989 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001990 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001991 }
1992
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001993 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001994 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001995 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001996 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001997 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1998 if (nai == null) return null;
1999 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002000 }
2001
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002002 /** Returns a NetworkInfo object for a network that doesn't exist. */
2003 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2004 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2005 getNetworkTypeName(networkType), "" /* subtypeName */);
2006 info.setIsAvailable(true);
2007 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2008 // background data is restricted.
2009 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2010 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2011 ? DetailedState.BLOCKED
2012 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002013 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2014 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002015 return info;
2016 }
2017
Lorenzo Colittia7574052021-01-19 01:33:05 +09002018 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002019 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2020 return null;
2021 }
2022 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002023 if (nai == null) {
2024 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002025 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002026 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2027 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002028 }
2029
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002030 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002031 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002032 public NetworkInfo getNetworkInfo(int networkType) {
2033 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002034 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002035 if (getVpnUnderlyingNetworks(uid) != null) {
2036 // A VPN is active, so we may need to return one of its underlying networks. This
2037 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002038 // getNetworkAgentInfoForUid.
2039 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2040 if (nai == null) return null;
2041 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2042 if (networkInfo.getType() == networkType) {
2043 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002044 }
2045 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002046 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002047 }
2048
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002049 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002050 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002051 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002052 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002053 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002054 if (nai == null) return null;
2055 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002056 }
2057
2058 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002059 public NetworkInfo[] getAllNetworkInfo() {
2060 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002061 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002062 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2063 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002064 NetworkInfo info = getNetworkInfo(networkType);
2065 if (info != null) {
2066 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002067 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002068 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002069 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002070 }
2071
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002072 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002073 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002074 public Network getNetworkForType(int networkType) {
2075 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002076 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2077 return null;
2078 }
2079 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2080 if (nai == null) {
2081 return null;
2082 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002083 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002084 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2085 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002086 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002087 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002088 }
2089
2090 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002091 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002092 public Network[] getAllNetworks() {
2093 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002094 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002095 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002096 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002097 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002098 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002099 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002100 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002101 }
2102
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002103 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002104 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002105 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002106 // The basic principle is: if an app's traffic could possibly go over a
2107 // network, without the app doing anything multinetwork-specific,
2108 // (hence, by "default"), then include that network's capabilities in
2109 // the array.
2110 //
2111 // In the normal case, app traffic only goes over the system's default
2112 // network connection, so that's the only network returned.
2113 //
2114 // With a VPN in force, some app traffic may go into the VPN, and thus
2115 // over whatever underlying networks the VPN specifies, while other app
2116 // traffic may go over the system default network (e.g.: a split-tunnel
2117 // VPN, or an app disallowed by the VPN), so the set of networks
2118 // returned includes the VPN's underlying networks and the system
2119 // default.
2120 enforceAccessPermission();
2121
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002122 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002123
James Mattis2516da32021-01-31 17:06:19 -08002124 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2125 if (!nri.isBeingSatisfied()) {
2126 continue;
2127 }
2128 final NetworkAgentInfo nai = nri.getSatisfier();
2129 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2130 if (null != nc
2131 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2132 && !result.containsKey(nai.network)) {
2133 result.put(
2134 nai.network,
2135 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002136 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002137 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2138 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002139 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002140 }
2141
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002142 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002143 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002144 if (null != networks) {
2145 for (final Network network : networks) {
2146 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2147 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002148 result.put(
2149 network,
2150 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002151 nc,
2152 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002153 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002154 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002155 }
2156 }
2157 }
2158
2159 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2160 out = result.values().toArray(out);
2161 return out;
2162 }
2163
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002164 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002165 public boolean isNetworkSupported(int networkType) {
2166 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002167 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002168 }
2169
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002170 /**
2171 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002172 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002173 * @return the ip properties for the active network, or {@code null} if
2174 * none is active
2175 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002176 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002177 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002178 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002179 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002180 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2181 if (nai == null) return null;
2182 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002183 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002184 }
2185
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002186 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002187 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002188 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002189 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002190 final LinkProperties lp = getLinkProperties(nai);
2191 if (lp == null) return null;
2192 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002193 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002194 }
2195
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002196 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002197 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002198 public LinkProperties getLinkProperties(Network network) {
2199 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002200 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2201 if (lp == null) return null;
2202 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002203 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002204 }
2205
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002206 @Nullable
2207 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002208 if (nai == null) {
2209 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002210 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002211 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002212 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002213 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002214 }
2215
lucaslinc582d502022-01-27 09:07:00 +08002216 @Override
2217 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002218 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002219 @NonNull String packageName, @Nullable String callingAttributionTag) {
2220 Objects.requireNonNull(packageName);
2221 Objects.requireNonNull(lp);
2222 enforceNetworkStackOrSettingsPermission();
2223 if (!checkAccessPermission(-1 /* pid */, uid)) {
2224 return null;
2225 }
2226 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2227 }
2228
Qingxi Lib2748102020-01-08 12:51:49 -08002229 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2230 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2231 }
2232
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002233 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002234 if (nai == null) return null;
2235 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002236 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002237 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002238 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002239 }
2240
2241 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002242 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2243 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002244 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002245 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002246 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002247 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002248 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002249 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002250 }
2251
lucaslinc582d502022-01-27 09:07:00 +08002252 @Override
lucaslind2b06132022-03-02 10:56:57 +08002253 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2254 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2255 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002256 Objects.requireNonNull(nc);
2257 Objects.requireNonNull(packageName);
2258 enforceNetworkStackOrSettingsPermission();
2259 if (!checkAccessPermission(-1 /* pid */, uid)) {
2260 return null;
2261 }
2262 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2263 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2264 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2265 callingAttributionTag);
2266 }
2267
lucaslin69e1aa92022-03-22 18:15:09 +08002268 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2269 if (nc.getUnderlyingNetworks() != null
2270 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2271 nc.setUnderlyingNetworks(null);
2272 }
2273 }
2274
Qingxi Libb8da982020-01-17 17:54:27 -08002275 @VisibleForTesting
2276 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002277 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002278 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2279 // this would be expensive (one more permission check every time any NC callback is
2280 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2281 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2282 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002283 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002284 if (!checkSettingsPermission(callerPid, callerUid)) {
2285 newNc.setUids(null);
2286 newNc.setSSID(null);
2287 }
Etan Cohen107ae952018-12-30 17:59:59 -08002288 if (newNc.getNetworkSpecifier() != null) {
2289 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2290 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002291 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2292 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2293 newNc.setAdministratorUids(new int[0]);
2294 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002295 if (!checkAnyPermissionOf(
2296 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002297 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002298 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002299 }
lucaslin69e1aa92022-03-22 18:15:09 +08002300 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002301
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002302 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002303 }
2304
Roshan Pius98f59ec2021-02-23 08:47:39 -08002305 /**
2306 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002307 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002308 * NetworkCapabilities.
2309 * Note: This wrapper does not support any sort of invalidation and thus must not be
2310 * persistent or long-lived. It may only be used for the time necessary to
2311 * compute the redactions required by one particular NetworkCallback or
2312 * synchronous call.
2313 */
2314 private class RedactionPermissionChecker {
2315 private final int mCallingPid;
2316 private final int mCallingUid;
2317 @NonNull private final String mCallingPackageName;
2318 @Nullable private final String mCallingAttributionTag;
2319
2320 private Boolean mHasLocationPermission = null;
2321 private Boolean mHasLocalMacAddressPermission = null;
2322 private Boolean mHasSettingsPermission = null;
2323
2324 RedactionPermissionChecker(int callingPid, int callingUid,
2325 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2326 mCallingPid = callingPid;
2327 mCallingUid = callingUid;
2328 mCallingPackageName = callingPackageName;
2329 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002330 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002331
2332 private boolean hasLocationPermissionInternal() {
2333 final long token = Binder.clearCallingIdentity();
2334 try {
2335 return mLocationPermissionChecker.checkLocationPermission(
2336 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2337 null /* message */);
2338 } finally {
2339 Binder.restoreCallingIdentity(token);
2340 }
2341 }
2342
2343 /**
2344 * Returns whether the app holds location permission or not (might return cached result
2345 * if the permission was already checked before).
2346 */
2347 public boolean hasLocationPermission() {
2348 if (mHasLocationPermission == null) {
2349 // If there is no cached result, perform the check now.
2350 mHasLocationPermission = hasLocationPermissionInternal();
2351 }
2352 return mHasLocationPermission;
2353 }
2354
2355 /**
2356 * Returns whether the app holds local mac address permission or not (might return cached
2357 * result if the permission was already checked before).
2358 */
2359 public boolean hasLocalMacAddressPermission() {
2360 if (mHasLocalMacAddressPermission == null) {
2361 // If there is no cached result, perform the check now.
2362 mHasLocalMacAddressPermission =
2363 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2364 }
2365 return mHasLocalMacAddressPermission;
2366 }
2367
2368 /**
2369 * Returns whether the app holds settings permission or not (might return cached
2370 * result if the permission was already checked before).
2371 */
2372 public boolean hasSettingsPermission() {
2373 if (mHasSettingsPermission == null) {
2374 // If there is no cached result, perform the check now.
2375 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2376 }
2377 return mHasSettingsPermission;
2378 }
2379 }
2380
2381 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2382 @NetworkCapabilities.NetCapability long redaction) {
2383 return (redactions & redaction) != 0;
2384 }
2385
2386 /**
2387 * Use the provided |applicableRedactions| to check the receiving app's
2388 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2389 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2390 * before being sent to the corresponding app.
2391 */
2392 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2393 @NetworkCapabilities.RedactionType long applicableRedactions,
2394 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2395 boolean includeLocationSensitiveInfo) {
2396 long redactions = applicableRedactions;
2397 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2398 if (includeLocationSensitiveInfo
2399 && redactionPermissionChecker.hasLocationPermission()) {
2400 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2401 }
2402 }
2403 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2404 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2405 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2406 }
2407 }
2408 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2409 if (redactionPermissionChecker.hasSettingsPermission()) {
2410 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2411 }
2412 }
2413 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002414 }
2415
Qingxi Lib2748102020-01-08 12:51:49 -08002416 @VisibleForTesting
2417 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002418 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002419 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002420 int callingPid, int callingUid, @NonNull String callingPkgName,
2421 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002422 if (nc == null) {
2423 return null;
2424 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002425 // Avoid doing location permission check if the transport info has no location sensitive
2426 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002427 final RedactionPermissionChecker redactionPermissionChecker =
2428 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2429 callingAttributionTag);
2430 final long redactions = retrieveRequiredRedactions(
2431 nc.getApplicableRedactions(), redactionPermissionChecker,
2432 includeLocationSensitiveInfo);
2433 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002434 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002435 // TODO : calling UID is redacted because apps should generally not know what UID is
2436 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002437 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002438 newNc.setOwnerUid(INVALID_UID);
2439 return newNc;
2440 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002441 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2442 if (nc.hasTransport(TRANSPORT_VPN)) {
2443 // Owner UIDs already checked above. No need to re-check.
2444 return newNc;
2445 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002446 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2447 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002448 // compatibility for older apps.
2449 if (!includeLocationSensitiveInfo
2450 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002451 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002452 newNc.setOwnerUid(INVALID_UID);
2453 return newNc;
2454 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002455 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002456 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002457 newNc.setOwnerUid(INVALID_UID);
2458 }
Qingxi Lib2748102020-01-08 12:51:49 -08002459 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002460 }
2461
lucaslinc582d502022-01-27 09:07:00 +08002462 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002463 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2464 LinkProperties lp, int callerPid, int callerUid) {
2465 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002466 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2467 // this would be expensive (one more permission check every time any LP callback is
2468 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2469 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2470 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002471
2472 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2473 final boolean needsSanitization =
2474 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2475 if (!needsSanitization) {
2476 return new LinkProperties(lp);
2477 }
2478
2479 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002480 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002481 }
2482
2483 final LinkProperties newLp = new LinkProperties(lp);
2484 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2485 // object gets parceled.
2486 newLp.setCaptivePortalApiUrl(null);
2487 newLp.setCaptivePortalData(null);
2488 return newLp;
2489 }
2490
Roshan Pius08c94fb2020-01-16 12:17:17 -08002491 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2492 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002493 // There is no need to track the effective UID of the request here. If the caller
2494 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002495 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002496 // Unprivileged apps can only pass in null or their own UID.
2497 if (nc.getUids() == null) {
2498 // If the caller passes in null, the callback will also match networks that do not
2499 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2500 // In this case, redact everything in the request immediately. This ensures that the
2501 // app is not able to get any redacted information by filing an unredacted request
2502 // and observing whether the request matches something.
2503 if (nc.getNetworkSpecifier() != null) {
2504 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2505 }
2506 } else {
2507 nc.setSingleUid(callerUid);
2508 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002509 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002510 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002511 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002512
2513 // Clear owner UID; this can never come from an app.
2514 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002515 }
2516
Chalard Jean38354d12018-03-20 19:13:57 +09002517 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002518 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002519 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2520 }
2521 }
2522
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002523 @Override
2524 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2525 enforceAccessPermission();
2526 final int callerUid = Binder.getCallingUid();
2527 final long token = Binder.clearCallingIdentity();
2528 try {
2529 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2530 } finally {
2531 Binder.restoreCallingIdentity(token);
2532 }
2533 }
2534
junyulaiebd15162021-03-03 12:09:05 +08002535 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002536 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002537 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002538 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002539 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002540
Serik Beketayev05130302021-01-15 16:47:25 -08002541 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002542 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002543 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2544 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002545 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002546 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002547 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002548 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2549 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002550 }
2551 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002552 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002553 }
2554
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002555 @Override
junyulaiebd15162021-03-03 12:09:05 +08002556 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002557 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002558 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002559 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002560
2561 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2562 for (Network network : getAllNetworks()) {
2563 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002564 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002565 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2566 // NetworkCapabilities, which may contain UIDs of apps to which the
2567 // network applies. Should the UIDs be cleared so as not to leak or
2568 // interfere ?
2569 result.add(nai.getNetworkStateSnapshot());
2570 }
2571 }
2572 return result;
2573 }
2574
2575 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002576 public boolean isActiveNetworkMetered() {
2577 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002578
Qingxi Lib2748102020-01-08 12:51:49 -08002579 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002580 if (caps != null) {
2581 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2582 } else {
2583 // Always return the most conservative value
2584 return true;
2585 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002586 }
2587
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002588 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002589 * Ensures that the system cannot call a particular method.
2590 */
2591 private boolean disallowedBecauseSystemCaller() {
2592 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002593 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2594 // for devices launched with Q and above. However, existing devices upgrading to Q and
2595 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002596 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002597 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002598 log("This method exists only for app backwards compatibility"
2599 + " and must not be called by system services.");
2600 return true;
2601 }
2602 return false;
2603 }
2604
paulhub2c28682021-08-18 18:35:54 +08002605 private int getAppUid(final String app, final UserHandle user) {
2606 final PackageManager pm =
2607 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2608 final long token = Binder.clearCallingIdentity();
2609 try {
2610 return pm.getPackageUid(app, 0 /* flags */);
2611 } catch (PackageManager.NameNotFoundException e) {
2612 return -1;
2613 } finally {
2614 Binder.restoreCallingIdentity(token);
2615 }
2616 }
2617
2618 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2619 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2620 if (getAppUid(packageName, user) != callingUid) {
2621 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2622 }
2623 }
2624
Lorenzo Colitti23862912018-09-28 11:31:55 +09002625 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002626 * Ensure that a network route exists to deliver traffic to the specified
2627 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002628 * @param networkType the type of the network over which traffic to the
2629 * specified host is to be routed
2630 * @param hostAddress the IP address of the host to which the route is
2631 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002632 * @return {@code true} on success, {@code false} on failure
2633 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002634 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002635 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2636 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002637 if (disallowedBecauseSystemCaller()) {
2638 return false;
2639 }
paulhub2c28682021-08-18 18:35:54 +08002640 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002641 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002642 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002643 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002644 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002645
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002646 InetAddress addr;
2647 try {
2648 addr = InetAddress.getByAddress(hostAddress);
2649 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002650 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002651 return false;
2652 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002653
The Android Open Source Project28527d22009-03-03 19:31:44 -08002654 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002655 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002656 return false;
2657 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002658
2659 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2660 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002661 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002662 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2663 } else {
2664 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2665 }
2666 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002667 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002668
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002669 DetailedState netState;
2670 synchronized (nai) {
2671 netState = nai.networkInfo.getDetailedState();
2672 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002673
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002674 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002675 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002676 log("requestRouteToHostAddress on down network "
2677 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002678 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002679 }
2680 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002681 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002682
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002683 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002684 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002685 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002686 LinkProperties lp;
2687 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002688 synchronized (nai) {
2689 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002690 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002691 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002692 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002693 if (DBG) {
2694 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2695 }
Wink Saville32506bc2013-06-29 21:10:57 -07002696 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002697 } finally {
2698 Binder.restoreCallingIdentity(token);
2699 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002700 }
2701
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002702 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002703 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002704 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002705 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002706 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002707 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002708 if (bestRoute.getGateway().equals(addr)) {
2709 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002710 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002711 } else {
2712 // if we will connect to this through another route, add a direct route
2713 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002714 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002715 }
2716 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002717 if (DBG) log("Adding legacy route " + bestRoute +
2718 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002719
2720 final String dst = bestRoute.getDestinationLinkAddress().toString();
2721 final String nextHop = bestRoute.hasGateway()
2722 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002723 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002724 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2725 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002726 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002727 return false;
2728 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002729 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002730 }
2731
paulhu7c0a2e62021-01-08 00:51:49 +08002732 class DnsResolverUnsolicitedEventCallback extends
2733 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002734 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002735 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002736 try {
2737 mHandler.sendMessage(mHandler.obtainMessage(
2738 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002739 new PrivateDnsValidationUpdate(event.netId,
2740 InetAddresses.parseNumericAddress(event.ipAddress),
2741 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002742 } catch (IllegalArgumentException e) {
2743 loge("Error parsing ip address in validation event");
2744 }
2745 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002746
2747 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002748 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2749 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002750 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2751 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2752 // event callback for certain nai. e.g. cellular. Register here to pass to
2753 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002754 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002755 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2756 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002757 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002758 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002759 }
2760 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002761
2762 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002763 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2764 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2765 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002766 }
dalyk1720e542018-03-05 12:42:22 -05002767
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002768 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002769 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002770 return this.VERSION;
2771 }
2772
2773 @Override
2774 public String getInterfaceHash() {
2775 return this.HASH;
2776 }
paulhu7c0a2e62021-01-08 00:51:49 +08002777 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002778
2779 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002780 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2781 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002782
paulhu7c0a2e62021-01-08 00:51:49 +08002783 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002784 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002785 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002786 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002787 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002788 }
2789 }
2790
Sudheer Shanka9967d462021-03-18 19:09:25 +00002791 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002792 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002793 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002794 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2795 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002796 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002797 };
2798
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002799 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002800 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002801 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002802 }
2803
paulhu1a407652019-03-22 16:35:06 +08002804 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2805 for (String permission : permissions) {
2806 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2807 return true;
2808 }
2809 }
2810 return false;
2811 }
2812
Paul Jensen83f5d572014-08-29 09:54:01 -04002813 private void enforceInternetPermission() {
2814 mContext.enforceCallingOrSelfPermission(
2815 android.Manifest.permission.INTERNET,
2816 "ConnectivityService");
2817 }
2818
The Android Open Source Project28527d22009-03-03 19:31:44 -08002819 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002820 mContext.enforceCallingOrSelfPermission(
2821 android.Manifest.permission.ACCESS_NETWORK_STATE,
2822 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002823 }
2824
lucaslinc582d502022-01-27 09:07:00 +08002825 private boolean checkAccessPermission(int pid, int uid) {
2826 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2827 == PERMISSION_GRANTED;
2828 }
2829
paulhua6ee2122021-02-22 15:40:43 +08002830 /**
2831 * Performs a strict and comprehensive check of whether a calling package is allowed to
2832 * change the state of network, as the condition differs for pre-M, M+, and
2833 * privileged/preinstalled apps. The caller is expected to have either the
2834 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2835 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2836 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2837 * permission and cannot be revoked. See http://b/23597341
2838 *
2839 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2840 * of this app will be updated to the current time.
2841 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002842 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002843 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2844 == PackageManager.PERMISSION_GRANTED) {
2845 return;
2846 }
2847
2848 if (callingPkg == null) {
2849 throw new SecurityException("Calling package name is null.");
2850 }
2851
2852 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2853 final int uid = mDeps.getCallingUid();
2854 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2855 callingPkg, callingAttributionTag, null /* message */);
2856
2857 if (mode == AppOpsManager.MODE_ALLOWED) {
2858 return;
2859 }
2860
2861 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2862 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2863 return;
2864 }
2865
2866 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2867 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2868 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002869 }
2870
Charles He9369e612017-05-15 17:07:18 +01002871 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002872 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002873 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002874 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002875 }
2876
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08002877 private void enforceSettingsOrUseRestrictedNetworksPermission() {
2878 enforceAnyPermissionOf(mContext,
2879 android.Manifest.permission.NETWORK_SETTINGS,
2880 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2881 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
2882 }
2883
paulhu8e96a752019-08-12 16:25:11 +08002884 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002885 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002886 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002887 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002888 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002889 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002890 }
2891
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002892 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002893 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002894 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002895 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002896 android.Manifest.permission.NETWORK_SETTINGS,
2897 android.Manifest.permission.NETWORK_FACTORY,
2898 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2899 }
2900
2901 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002902 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002903 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002904 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002905 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2906 android.Manifest.permission.NETWORK_FACTORY,
2907 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2908 }
2909
lucaslin69e1aa92022-03-22 18:15:09 +08002910 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2911 return PERMISSION_GRANTED == mContext.checkPermission(
2912 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2913 || PERMISSION_GRANTED == mContext.checkPermission(
2914 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2915 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002916 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002917 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002918 }
2919
Chalard Jean9a396cc2018-02-21 18:43:54 +09002920 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002921 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002922 android.Manifest.permission.NETWORK_SETTINGS,
2923 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002924 }
2925
2926 private boolean checkSettingsPermission(int pid, int uid) {
2927 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002928 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2929 || PERMISSION_GRANTED == mContext.checkPermission(
2930 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002931 }
2932
paulhu8e96a752019-08-12 16:25:11 +08002933 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002934 enforceNetworkStackPermissionOr(mContext,
2935 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002936 }
2937
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002938 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002939 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002940 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002941 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002942 }
2943
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002944 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002945 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002946 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2947 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002948 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002949 }
2950
James Mattis8378aec2021-01-26 14:05:36 -08002951 private void enforceOemNetworkPreferencesPermission() {
2952 mContext.enforceCallingOrSelfPermission(
2953 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2954 "ConnectivityService");
2955 }
2956
James Mattisfa270db2021-05-31 17:11:10 -07002957 private void enforceManageTestNetworksPermission() {
2958 mContext.enforceCallingOrSelfPermission(
2959 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2960 "ConnectivityService");
2961 }
2962
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002963 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002964 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002965 android.Manifest.permission.NETWORK_STACK,
2966 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002967 }
2968
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002969 private boolean checkNetworkStackPermission(int pid, int uid) {
2970 return checkAnyPermissionOf(pid, uid,
2971 android.Manifest.permission.NETWORK_STACK,
2972 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2973 }
2974
paulhu1a407652019-03-22 16:35:06 +08002975 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2976 return checkAnyPermissionOf(pid, uid,
2977 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002978 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2979 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002980 }
2981
Paul Hu8fc2a552022-05-04 18:44:42 +08002982 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
2983 boolean checkUidsAllowedList) {
2984 if (PermissionUtils.checkAnyPermissionOf(mContext,
2985 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
2986 return true;
2987 }
2988
2989 // fallback to ConnectivityInternalPermission
2990 // TODO: Remove this fallback check after all apps have declared
2991 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2992 if (PermissionUtils.checkAnyPermissionOf(mContext,
2993 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
2994 return true;
2995 }
2996
2997 // Check whether uid is in allowed on restricted networks list.
2998 if (checkUidsAllowedList
2999 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3000 return true;
3001 }
3002 return false;
3003 }
3004
3005 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3006 final int callingUid = mDeps.getCallingUid();
3007 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3008 throw new SecurityException("ConnectivityService: user " + callingUid
3009 + " has no permission to access restricted network.");
3010 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003011 }
3012
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003013 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003014 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003015 }
3016
Roshan Pius98f59ec2021-02-23 08:47:39 -08003017 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3018 return PERMISSION_GRANTED == mContext.checkPermission(
3019 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3020 }
3021
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003022 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003023 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003024 }
3025
3026 private void sendInetConditionBroadcast(NetworkInfo info) {
3027 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3028 }
3029
Wink Saville4f0de1e2011-08-04 15:01:58 -07003030 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003031 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003032 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003033 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003034 if (info.isFailover()) {
3035 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3036 info.setFailover(false);
3037 }
3038 if (info.getReason() != null) {
3039 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3040 }
3041 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003042 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3043 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003044 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003045 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003046 return intent;
3047 }
3048
3049 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3050 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3051 }
3052
Michael Groover73f69482023-01-27 11:01:25 -06003053 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3054 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003055 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3056 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003057 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003058 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003059 if (!mSystemReady
3060 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003061 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003062 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003063 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003064 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003065 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003066 }
3067
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003068 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003069 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003070 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003071 final NetworkInfo ni = intent.getParcelableExtra(
3072 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003073 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3074 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003075 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003076 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003077 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003078 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003079 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003080 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003081 } finally {
3082 Binder.restoreCallingIdentity(ident);
3083 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003084 }
3085 }
3086
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003087 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3088 NetworkInfo info) {
3089 // Delivery group policy APIs are only available on U+.
3090 if (!SdkLevel.isAtLeastU()) return;
3091
3092 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3093 try {
3094 // This allows us to discard older broadcasts still waiting to be delivered
3095 // which have the same namespace and key.
3096 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3097 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3098 createDeliveryGroupKeyForConnectivityAction(info));
Sudheer Shanka74fe7172023-01-24 19:33:06 +00003099 optsShim.setDeferUntilActive(true);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003100 } catch (UnsupportedApiLevelException e) {
3101 Log.wtf(TAG, "Using unsupported API" + e);
3102 }
3103 }
3104
3105 @VisibleForTesting
3106 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3107 final StringBuilder sb = new StringBuilder();
3108 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3109 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3110 sb.append(info.getExtraInfo());
3111 return sb.toString();
3112 }
3113
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003114 /**
Aaron Huang96011892020-06-27 07:18:23 +08003115 * Called by SystemServer through ConnectivityManager when the system is ready.
3116 */
3117 @Override
3118 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003119 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003120 throw new SecurityException("Calling Uid is not system uid.");
3121 }
3122 systemReadyInternal();
3123 }
3124
3125 /**
3126 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003127 */
3128 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003129 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003130 // Load flags after PackageManager is ready to query module version
3131 mFlags.loadFlags(mDeps, mContext);
3132
Aaron Huang9a57acf2020-12-08 10:03:29 +08003133 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3134 // listening network request which is sent by MultipathPolicyTracker won't be added
3135 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3136 // be called after PermissionMonitor#startMonitoring().
3137 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3138 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3139 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003140 final ConditionVariable startMonitoringDone = new ConditionVariable();
3141 mHandler.post(() -> {
3142 mPermissionMonitor.startMonitoring();
3143 startMonitoringDone.open();
3144 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003145 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003146 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003147
Hugo Benichie5220992017-04-26 14:53:28 +09003148 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003149 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003150 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003151 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003152 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003153 }
3154 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003155
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003156 // Create network requests for always-on networks.
3157 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003158
3159 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003160 // Note that updating can be skipped here if the list is empty only because no uid
3161 // rules are applied before system ready. Normally, the empty uid list means to clear
3162 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003163 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3164 updateMobileDataPreferredUids();
3165 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003166
3167 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3168 if (SdkLevel.isAtLeastT()) {
3169 mBpfNetMaps.setPullAtomCallback(mContext);
3170 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003171 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3172 // have permission problem. While CV#block() is unbounded in time and can in principle block
3173 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3174 // could have blocked forever too.
3175 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003176 }
3177
The Android Open Source Project28527d22009-03-03 19:31:44 -08003178 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003179 * Start listening for default data network activity state changes.
3180 */
3181 @Override
3182 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003183 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003184 }
3185
3186 /**
3187 * Stop listening for default data network activity state changes.
3188 */
3189 @Override
3190 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003191 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003192 }
3193
3194 /**
3195 * Check whether the default network radio is currently active.
3196 */
3197 @Override
3198 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003199 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003200 }
3201
3202 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003203 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003204 * and set it on it's iface.
3205 */
Junyu Lai970963e2022-10-25 15:46:47 +08003206 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003207 final String iface = newLp.getInterfaceName();
3208 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003209 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003210 // Silently ignore unset MTU value.
3211 return;
3212 }
Hansen Kurli04252032022-12-07 11:21:49 +00003213 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3214 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3215 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003216 return;
3217 }
Hansen Kurli04252032022-12-07 11:21:49 +00003218 // Cannot set MTU without interface name
3219 if (TextUtils.isEmpty(iface)) {
3220 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003221 return;
3222 }
sy.yun4aa73922013-09-02 05:24:09 +09003223
Hansen Kurli04252032022-12-07 11:21:49 +00003224 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3225 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003226 return;
3227 }
3228
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003229 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003230 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003231 mNetd.interfaceSetMtu(iface, mtu);
3232 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003233 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003234 }
3235 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003236
Chenbo Feng15416292018-11-08 17:36:21 -08003237 @VisibleForTesting
3238 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003239
Junyu Lai970963e2022-10-25 15:46:47 +08003240 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003241 String[] values = null;
3242 if (tcpBufferSizes != null) {
3243 values = tcpBufferSizes.split(",");
3244 }
3245
3246 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003247 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003248 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3249 values = tcpBufferSizes.split(",");
3250 }
3251
3252 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3253
3254 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003255 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003256
Chenbo Feng15416292018-11-08 17:36:21 -08003257 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3258 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3259 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003260 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003261 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003262 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003263 }
3264 }
3265
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003266 @Override
3267 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003268 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003269 NETWORK_RESTORE_DELAY_PROP_NAME);
3270 if(restoreDefaultNetworkDelayStr != null &&
3271 restoreDefaultNetworkDelayStr.length() != 0) {
3272 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003273 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003274 } catch (NumberFormatException e) {
3275 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003276 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003277 // if the system property isn't set, use the value for the apn type
3278 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3279
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003280 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3281 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003282 }
3283 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003284 }
3285
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003286 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003287 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003288 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003289 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003290 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003291 // Start gathering diagnostic information.
3292 netDiags.add(new NetworkDiagnostics(
3293 nai.network,
3294 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003295 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003296 DIAG_TIME_MS));
3297 }
3298
3299 for (NetworkDiagnostics netDiag : netDiags) {
3300 pw.println();
3301 netDiag.waitForMeasurements();
3302 netDiag.dump(pw);
3303 }
3304 }
3305
The Android Open Source Project28527d22009-03-03 19:31:44 -08003306 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003307 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3308 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003309 if (!checkDumpPermission(mContext, TAG, writer)) return;
3310
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003311 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003312 }
3313
lucaslin99473f62020-12-10 15:10:54 +08003314 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3315 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3316 != PackageManager.PERMISSION_GRANTED) {
3317 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003318 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003319 + " due to missing android.permission.DUMP permission");
3320 return false;
3321 } else {
3322 return true;
3323 }
3324 }
3325
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003326 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003327 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003328
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003329 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003330 dumpNetworkDiagnostics(pw);
3331 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003332 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003333 dumpNetworks(pw);
3334 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003335 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003336 dumpNetworkRequests(pw);
3337 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003338 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3339 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3340 dumpTrafficController(pw, fd, verbose);
3341 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003342 }
Erik Kline9647f382015-06-05 17:47:34 +09003343
Junyu Lai0da479b2022-04-20 15:06:29 +08003344 pw.println("NetworkProviders for:");
3345 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003346 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003347 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003348 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003349 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003350 pw.println();
3351
Chalard Jean5b409c72021-02-04 13:12:59 +09003352 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003353 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003354 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003355 pw.println("none");
3356 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003357 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003358 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003359 pw.println();
3360
James Mattis8b298a02021-06-01 22:34:04 -07003361 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003362 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003363 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003364 pw.decreaseIndent();
3365 pw.println();
3366
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003367 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003368 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003369 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003370 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003371 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003372
junyulaif2c67e42018-08-07 19:50:45 +08003373 pw.println("Status for known UIDs:");
3374 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003375 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003376 for (int i = 0; i < size; i++) {
3377 // Don't crash if the array is modified while dumping in bugreports.
3378 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003379 final int uid = mUidBlockedReasons.keyAt(i);
3380 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3381 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003382 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003383 } catch (ArrayIndexOutOfBoundsException e) {
3384 pw.println(" ArrayIndexOutOfBoundsException");
3385 } catch (ConcurrentModificationException e) {
3386 pw.println(" ConcurrentModificationException");
3387 }
3388 }
3389 pw.println();
3390 pw.decreaseIndent();
3391
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003392 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003393 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003394 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003395 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003396 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003397
Junyu Lai0da479b2022-04-20 15:06:29 +08003398 pw.println("Network Offers:");
3399 pw.increaseIndent();
3400 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3401 pw.println(offerInfo.offer);
3402 }
3403 pw.decreaseIndent();
3404 pw.println();
3405
Robert Greenwalt94e22142014-07-30 16:31:24 -07003406 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003407
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003408 pw.println();
markchien5e866652019-09-30 14:40:57 +08003409 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003410
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003411 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003412 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003413
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003414 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003415
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003416 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003417 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003418 pw.println("mNetworkRequestInfoLogs (most recent first):");
3419 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003420 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003421 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003422
3423 pw.println();
3424 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3425 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003426 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003427 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003428
3429 pw.println();
3430 pw.println("NetTransition WakeLock activity (most recent first):");
3431 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003432 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3433 pw.println("total releases: " + mTotalWakelockReleases);
3434 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3435 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3436 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3437 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3438 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3439 }
James Mattiscb1e0362021-04-06 17:07:42 -07003440 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003441
3442 pw.println();
3443 pw.println("bandwidth update requests (by uid):");
3444 pw.increaseIndent();
3445 synchronized (mBandwidthRequests) {
3446 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3447 pw.println("[" + mBandwidthRequests.keyAt(i)
3448 + "]: " + mBandwidthRequests.valueAt(i));
3449 }
3450 }
3451 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003452 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003453
James Mattiscb1e0362021-04-06 17:07:42 -07003454 pw.println();
3455 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3456 pw.increaseIndent();
3457 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003458 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003459 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003460
3461 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003462
3463 pw.println();
3464 pw.println("Permission Monitor:");
3465 pw.increaseIndent();
3466 mPermissionMonitor.dump(pw);
3467 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003468
3469 pw.println();
3470 pw.println("Legacy network activity:");
3471 pw.increaseIndent();
3472 mNetworkActivityTracker.dump(pw);
3473 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003474 }
3475
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003476 private void dumpNetworks(IndentingPrintWriter pw) {
3477 for (NetworkAgentInfo nai : networksSortedById()) {
3478 pw.println(nai.toString());
3479 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003480 pw.println("Nat464Xlat:");
3481 pw.increaseIndent();
3482 nai.dumpNat464Xlat(pw);
3483 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003484 pw.println(String.format(
3485 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3486 nai.numForegroundNetworkRequests(),
3487 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3488 nai.numBackgroundNetworkRequests(),
3489 nai.numNetworkRequests()));
3490 pw.increaseIndent();
3491 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3492 pw.println(nai.requestAt(i).toString());
3493 }
3494 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003495 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003496 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003497 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003498 pw.decreaseIndent();
3499 pw.decreaseIndent();
3500 }
3501 }
3502
James Mattis8b298a02021-06-01 22:34:04 -07003503 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3504 if (!mProfileNetworkPreferences.isEmpty()) {
3505 pw.println("Profile preferences:");
3506 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003507 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003508 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003509 }
James Mattis8b298a02021-06-01 22:34:04 -07003510 if (!mOemNetworkPreferences.isEmpty()) {
3511 pw.println("OEM preferences:");
3512 pw.increaseIndent();
3513 pw.println(mOemNetworkPreferences);
3514 pw.decreaseIndent();
3515 }
3516 if (!mMobileDataPreferredUids.isEmpty()) {
3517 pw.println("Mobile data preferred UIDs:");
3518 pw.increaseIndent();
3519 pw.println(mMobileDataPreferredUids);
3520 pw.decreaseIndent();
3521 }
James Mattis45d81842021-01-10 14:24:24 -08003522
James Mattis8b298a02021-06-01 22:34:04 -07003523 pw.println("Default requests:");
3524 pw.increaseIndent();
3525 dumpPerAppDefaultRequests(pw);
3526 pw.decreaseIndent();
3527 }
3528
3529 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003530 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3531 if (mDefaultRequest == defaultRequest) {
3532 continue;
3533 }
3534
James Mattis8b298a02021-06-01 22:34:04 -07003535 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3536 final String networkOutput;
3537 if (null == satisfier) {
3538 networkOutput = "null";
3539 } else if (mNoServiceNetwork.equals(satisfier)) {
3540 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003541 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003542 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003543 }
James Mattis8b298a02021-06-01 22:34:04 -07003544 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3545 ? "" : " asUid: " + defaultRequest.mAsUid;
3546 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3547 + defaultRequest.mPid + asUidString + "]";
3548 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3549 + " Preference order: " + defaultRequest.mPreferenceOrder
3550 + " Tracked UIDs: " + defaultRequest.getUids();
3551 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003552 }
3553 }
3554
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003555 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003556 NetworkRequestInfo[] infos = null;
3557 while (infos == null) {
3558 try {
3559 infos = requestsSortedById();
3560 } catch (ConcurrentModificationException e) {
3561 // mNetworkRequests should only be accessed from handler thread, except dump().
3562 // As dump() is never called in normal usage, it would be needlessly expensive
3563 // to lock the collection only for its benefit. Instead, retry getting the
3564 // requests if ConcurrentModificationException is thrown during dump().
3565 }
3566 }
3567 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003568 pw.println(nri.toString());
3569 }
3570 }
3571
Ken Chene6d511f2022-01-25 11:10:42 +08003572 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3573 boolean verbose) {
3574 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003575 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003576 } catch (ServiceSpecificException e) {
3577 pw.println(e.getMessage());
3578 } catch (IOException e) {
3579 loge("Dump BPF maps failed, " + e);
3580 }
3581 }
3582
Chalard Jean524f0b12021-10-25 21:11:56 +09003583 private void dumpAllRequestInfoLogsToLogcat() {
3584 try (PrintWriter logPw = new PrintWriter(new Writer() {
3585 @Override
3586 public void write(final char[] cbuf, final int off, final int len) {
3587 // This method is called with 0-length and 1-length arrays for empty strings
3588 // or strings containing only the DEL character.
3589 if (len <= 1) return;
3590 Log.e(TAG, new String(cbuf, off, len));
3591 }
3592 @Override public void flush() {}
3593 @Override public void close() {}
3594 })) {
3595 mNetworkRequestInfoLogs.dump(logPw);
3596 }
3597 }
3598
Hugo Benichia480ba52018-09-03 08:19:02 +09003599 /**
3600 * Return an array of all current NetworkAgentInfos sorted by network id.
3601 */
3602 private NetworkAgentInfo[] networksSortedById() {
3603 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003604 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003605 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003606 return networks;
3607 }
3608
3609 /**
3610 * Return an array of all current NetworkRequest sorted by request id.
3611 */
James Mattis258ea3c2020-11-15 15:04:40 -08003612 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003613 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003614 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003615 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003616 // Sort the array based off the NRI containing the min requestId in its requests.
3617 Arrays.sort(requests,
3618 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3619 Comparator.comparingInt(req -> req.requestId)).requestId
3620 )
3621 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003622 return requests;
3623 }
3624
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003625 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003626 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003627 if (officialNai != null && officialNai.equals(nai)) return true;
3628 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003629 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003630 " - " + nai);
3631 }
3632 return false;
3633 }
3634
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003635 private boolean isDisconnectRequest(Message msg) {
3636 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3637 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3638 return info.getState() == NetworkInfo.State.DISCONNECTED;
3639 }
3640
Robert Greenwalt2034b912009-08-12 16:08:25 -07003641 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003642 private class NetworkStateTrackerHandler extends Handler {
3643 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003644 super(looper);
3645 }
3646
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003647 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003648 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3649 final NetworkAgentInfo nai = arg.first;
3650 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003651 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003652 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003653 }
3654 return;
3655 }
3656
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003657 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003658 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003659 return;
3660 }
3661
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003662 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003663 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003664 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3665 final NetworkCapabilities sanitized =
3666 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003667 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003668 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003669 break;
3670 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003671 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003672 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003673 processLinkPropertiesFromAgent(nai, newLp);
3674 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003675 break;
3676 }
3677 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003678 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003679 updateNetworkInfo(nai, info);
3680 break;
3681 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003682 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003683 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003684 break;
3685 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003686 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003687 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003688 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003689 // Note that if the NAI had been connected, this would affect the
3690 // score, and therefore would require re-mixing the score and performing
3691 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003692 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003693 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3694 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003695 // Mark the network as temporarily accepting partial connectivity so that it
3696 // will be validated (and possibly become default) even if it only provides
3697 // partial internet access. Note that if user connects to partial connectivity
3698 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3699 // out of wifi coverage) and if the same wifi is available again, the device
3700 // will auto connect to this wifi even though the wifi has "no internet".
3701 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003702 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003703 break;
3704 }
junyulai011b1f12019-01-03 18:50:15 +08003705 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003706 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003707 break;
3708 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003709 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003710 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003711 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003712
3713 if (isLegacyLockdownNai(nai)
3714 && (underlying == null || underlying.size() != 1)) {
3715 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3716 + " must have exactly one underlying network: " + underlying);
3717 }
3718
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003719 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3720 nai.declaredUnderlyingNetworks = (underlying != null)
3721 ? underlying.toArray(new Network[0]) : null;
3722
3723 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3724 if (DBG) {
3725 log(nai.toShortString() + " changed underlying networks to "
3726 + Arrays.toString(nai.declaredUnderlyingNetworks));
3727 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003728 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003729 notifyIfacesChangedForNetworkStats();
3730 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003731 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003732 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003733 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3734 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3735 nai.teardownDelayMs = msg.arg1;
3736 } else {
3737 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3738 }
Chalard Jean550b5212021-03-05 23:07:53 +09003739 break;
3740 }
3741 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3742 nai.setLingerDuration((int) arg.second);
3743 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003744 }
Tyler Wear72388212021-09-09 14:49:02 -07003745 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3746 DscpPolicy policy = (DscpPolicy) arg.second;
3747 if (mDscpPolicyTracker != null) {
3748 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3749 }
3750 break;
3751 }
3752 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3753 if (mDscpPolicyTracker != null) {
3754 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3755 }
3756 break;
3757 }
3758 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3759 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003760 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003761 }
3762 break;
3763 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003764 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09003765 if (!nai.isCreated()) {
3766 Log.d(TAG, "unregisterAfterReplacement on uncreated " + nai.toShortString()
3767 + ", tearing down instead");
3768 teardownUnneededNetwork(nai);
3769 break;
3770 }
3771
3772 if (nai.isDestroyed()) {
3773 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
3774 + ", ignoring");
3775 break;
3776 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003777
3778 final int timeoutMs = (int) arg.second;
3779 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3780 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3781 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3782 }
3783
3784 // Marking a network awaiting replacement is used to ensure that any requests
3785 // satisfied by the network do not switch to another network until a
3786 // replacement is available or the wait for a replacement times out.
3787 // If the network is inactive (i.e., nascent or lingering), then there are no
3788 // such requests, and there is no point keeping it. Just tear it down.
3789 // Note that setLingerDuration(0) cannot be used to do this because the network
3790 // could be nascent.
3791 nai.clearInactivityState();
3792 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3793 Log.d(TAG, nai.toShortString()
3794 + " marked awaiting replacement is unneeded, tearing down instead");
3795 teardownUnneededNetwork(nai);
3796 break;
3797 }
3798
3799 Log.d(TAG, "Marking " + nai.toShortString()
3800 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3801 destroyNativeNetwork(nai);
3802
3803 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3804 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3805 // consider the fact that the network could already have disconnected or been
3806 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3807 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3808 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3809 mKeepaliveTracker.handleStopAllKeepalives(nai,
3810 SocketKeepalive.ERROR_INVALID_NETWORK);
3811
3812 nai.updateScoreForNetworkAgentUpdate();
3813 // This rematch is almost certainly not going to result in any changes, because
3814 // the destroyed flag is only just above the "current satisfier wins"
3815 // tie-breaker. But technically anything that affects scoring should rematch.
3816 rematchAllNetworksAndRequests();
3817 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3818 break;
3819 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003820 }
3821 }
3822
3823 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003824 final int netId = msg.arg2;
3825 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003826 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003827 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003828 switch (msg.what) {
3829 default:
3830 return false;
lucasline117e2e2019-10-22 18:27:33 +08003831 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003832 if (nai == null) {
3833 break;
3834 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003835 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3836 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003837 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003838 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003839 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003840 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003841 if (probePrivateDnsCompleted) {
3842 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3843 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003844 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003845 }
3846 // Only show the notification when the private DNS is broken and the
3847 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003848 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003849 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3850 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003851 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003852 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3853 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3854 // private DNS is broken, it means this network is being reevaluated.
3855 // Either probing private DNS is not necessary any more or it hasn't been
3856 // done yet. In either case, the networkCapabilities should be updated to
3857 // reflect the new status.
3858 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003859 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003860 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003861 }
3862 break;
3863 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003864 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003865 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3866
Erik Kline31b4a9e2018-01-11 21:07:29 +09003867 if (nai == null) break;
3868
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003869 handleNetworkTested(nai, results.mTestResult,
3870 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003871 break;
3872 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003873 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003874 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003875 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003876 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003877 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003878 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003879 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3880 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003881 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003882 if (nai == null) {
3883 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3884 break;
3885 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003886 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003887 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003888 (PendingIntent) msg.obj,
3889 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003890 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003891 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003892 break;
3893 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003894 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003895 if (nai == null) break;
3896
Erik Kline9a62f012018-03-21 07:18:33 -07003897 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003898 break;
3899 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003900 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003901 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003902 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003903 break;
3904 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003905 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003906 return true;
3907 }
3908
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003909 private void handleNetworkTested(
3910 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09003911 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
3912 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09003913 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003914
3915 // If there is any kind of working networking, then the NAI has been evaluated
3916 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
3917 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09003918 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003919 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09003920 // Because of b/245893397, if the score is updated when updateCapabilities is called,
3921 // any callback that receives onAvailable for that rematch receives an extra caps
3922 // callback. To prevent that, update the score in the agent so the updates below won't
3923 // see an update to both caps and score at the same time.
3924 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003925 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
3926
he_won.hwang881307a2022-03-15 21:23:52 +09003927 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3928 // Assume the validation failure is due to a temporary failure after roaming
3929 // and ignore it. NetworkMonitor will continue to retry validation. If it
3930 // continues to fail after the block timeout expires, the network will be
3931 // marked unvalidated. If it succeeds, then validation state will not change.
3932 return;
3933 }
3934
Chalard Jean254bd162022-08-25 13:04:51 +09003935 final boolean wasValidated = nai.isValidated();
3936 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09003937 final boolean wasPortal = nai.captivePortalDetected();
3938 nai.setPartialConnectivity(partial);
3939 nai.setCaptivePortalDetected(portal);
3940 nai.updateScoreForNetworkAgentUpdate();
3941 final boolean partialConnectivityChanged = (wasPartial != partial);
3942 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003943
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003944 if (DBG) {
3945 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3946 ? " with redirect to " + redirectUrl
3947 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003948 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003949 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09003950 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003951 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003952 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003953 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003954 if (valid) {
3955 handleFreshlyValidatedNetwork(nai);
3956 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3957 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003958 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003959 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003960 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003961 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003962 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003963 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003964 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003965 NotificationType.PRIVATE_DNS_BROKEN);
3966 // If network becomes valid, the hasShownBroken should be reset for
3967 // that network so that the notification will be fired when the private
3968 // DNS is broken again.
3969 nai.networkAgentConfig.hasShownBroken = false;
3970 }
3971 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003972 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09003973 } else if (portalChanged) {
3974 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3975 == getCaptivePortalMode()) {
3976 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3977 nai.onPreventAutomaticReconnect();
3978 teardownUnneededNetwork(nai);
3979 return;
3980 } else {
3981 updateCapabilitiesForNetwork(nai);
3982 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09003983 } else if (becameEvaluated) {
3984 // If valid or partial connectivity changed, updateCapabilities* has
3985 // done the rematch.
3986 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003987 }
3988 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003989
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003990 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003991 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003992 nai.onValidationStatusChanged(
3993 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3994 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003995
3996 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09003997 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003998 // immediately. Re-notify partial connectivity silently if no internet
3999 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004000 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004001 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004002 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4003 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004004 }
4005
Chalard Jean254bd162022-08-25 13:04:51 +09004006 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004007 handleNetworkUnvalidated(nai);
4008 }
4009 }
4010
Calvin Ondada1452016-10-11 15:10:46 -07004011 private int getCaptivePortalMode() {
4012 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004013 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4014 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004015 }
4016
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004017 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4018 switch (msg.what) {
4019 default:
4020 return false;
4021 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4022 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4023 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4024 handleLingerComplete(nai);
4025 }
4026 break;
4027 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004028 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4029 handleNetworkAgentRegistered(msg);
4030 break;
4031 }
4032 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4033 handleNetworkAgentDisconnected(msg);
4034 break;
4035 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004036 }
4037 return true;
4038 }
4039
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004040 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004041 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004042 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004043 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004044 maybeHandleNetworkAgentMessage(msg);
4045 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004046 }
4047 }
4048
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004049 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004050 private final int mNetId;
4051 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004052
4053 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004054 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004055 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004056 }
4057
4058 @Override
4059 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4060 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004061 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004062 }
4063
4064 @Override
4065 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004066 // Legacy version of notifyNetworkTestedWithExtras.
4067 // Would only be called if the system has a NetworkStack module older than the
4068 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004069 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004070 }
4071
4072 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004073 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004074 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4075 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004076 final Message msg = mTrackerHandler.obtainMessage(
4077 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004078 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004079 new NetworkTestedResults(
4080 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004081 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004082
4083 // Invoke ConnectivityReport generation for this Network test event.
4084 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4085 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004086
Cody Kestingf1120be2020-08-03 18:01:40 -07004087 // NetworkMonitor reports the network validation result as a bitmask while
4088 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4089 // logical value for ConnectivityDiagnostics.
4090 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4091 p.result);
4092
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004093 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004094 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004095 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4096 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4097
Aaron Huang959d3642021-01-21 15:47:41 +08004098 ConnectivityReportEvent reportEvent =
4099 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4100 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004101 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004102 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004103 }
4104
4105 @Override
4106 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4107 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4108 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004109 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004110 }
4111
4112 @Override
lucasline117e2e2019-10-22 18:27:33 +08004113 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4114 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4115 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004116 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004117 }
4118
4119 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004120 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4121 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4122 EVENT_CAPPORT_DATA_CHANGED,
4123 0, mNetId, data));
4124 }
4125
4126 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004127 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004128 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004129 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004130
4131 final PendingIntent pendingIntent;
4132 // Only the system server can register notifications with package "android"
4133 final long token = Binder.clearCallingIdentity();
4134 try {
paulhu7746e4e2020-06-09 19:07:03 +08004135 pendingIntent = PendingIntent.getBroadcast(
4136 mContext,
4137 0 /* requestCode */,
4138 intent,
4139 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004140 } finally {
4141 Binder.restoreCallingIdentity(token);
4142 }
4143 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4144 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004145 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004146 }
4147
4148 @Override
4149 public void hideProvisioningNotification() {
4150 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004151 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004152 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004153
4154 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004155 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004156 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004157 }
4158
4159 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004160 public int getInterfaceVersion() {
4161 return this.VERSION;
4162 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004163
4164 @Override
4165 public String getInterfaceHash() {
4166 return this.HASH;
4167 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004168 }
4169
Cody Kestingf1120be2020-08-03 18:01:40 -07004170 /**
4171 * Converts the given NetworkMonitor-specific validation result bitmask to a
4172 * ConnectivityDiagnostics-specific validation result int.
4173 */
4174 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4175 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4176 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4177 }
4178 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4179 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4180 }
4181 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4182 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4183 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4184 }
4185
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004186 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004187 log("Data stall detected with methods: " + p.detectionMethod);
4188
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004189 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004190 int detectionMethod = 0;
4191 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4192 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4193 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4194 }
4195 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4196 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4197 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4198 p.tcpMetricsCollectionPeriodMillis);
4199 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004200 }
4201
Cody Kestingf53a0752020-04-15 12:33:28 -07004202 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004203 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004204 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004205
4206 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4207 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4208 // the cost of going through two handlers.
4209 mConnectivityDiagnosticsHandler.sendMessage(msg);
4210 }
4211
Cody Kestingb37958e2020-05-15 10:36:01 -07004212 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4213 return (p.detectionMethod & detectionMethod) != 0;
4214 }
4215
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004216 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4217 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004218 }
4219
Erik Klinea73af002018-06-26 18:53:43 +09004220 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4221 if (nai == null) return;
4222 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4223 // in order to restart a validation pass from within netd.
4224 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4225 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004226 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004227 }
4228 }
4229
Erik Kline31b4a9e2018-01-11 21:07:29 +09004230 private void handlePrivateDnsSettingsChanged() {
4231 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4232
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004233 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004234 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004235 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004236 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4237 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004238 }
4239 }
4240
Erik Kline9a62f012018-03-21 07:18:33 -07004241 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4242 // Private DNS only ever applies to networks that might provide
4243 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004244 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004245
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004246 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004247 // schedule DNS resolutions. If a DNS resolution is required the
4248 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004249 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004250
4251 // With Private DNS bypass support, we can proceed to update the
4252 // Private DNS config immediately, even if we're in strict mode
4253 // and have not yet resolved the provider name into a set of IPs.
4254 updatePrivateDns(nai, cfg);
4255 }
4256
4257 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4258 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004259 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004260 }
4261
dalyk1720e542018-03-05 12:42:22 -05004262 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4263 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4264 if (nai == null) {
4265 return;
4266 }
4267 mDnsManager.updatePrivateDnsValidation(update);
4268 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4269 }
4270
paulhu7c0a2e62021-01-08 00:51:49 +08004271 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004272 int prefixLength) {
4273 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4274 if (nai == null) return;
4275
paulhu7c0a2e62021-01-08 00:51:49 +08004276 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4277 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004278
4279 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004280 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004281 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004282 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004283 prefixLength);
4284 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004285 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004286 return;
4287 }
4288 }
4289
Lorenzo Colittid523d142020-04-01 20:16:30 +09004290 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004291 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4292 }
4293
Hai Shalome58bdc62021-01-11 18:45:34 -08004294 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004295 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004296 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004297 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4298 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4299 }
4300
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004301 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004302 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004303 * @param nai the agent info to update
4304 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004305 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004306 */
junyulai2b6f0c22021-02-03 20:15:30 +08004307 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4308 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4309 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004310 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004311 // one lingered request, set inactive.
4312 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004313 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004314 if (DBG) log("Unsetting inactive " + nai.toShortString());
4315 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004316 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004317 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004318 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004319 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4320 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004321 }
junyulai2b6f0c22021-02-03 20:15:30 +08004322 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004323 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004324 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004325 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004326 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004327 }
4328
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004329 private void handleNetworkAgentRegistered(Message msg) {
4330 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4331 if (!mNetworkAgentInfos.contains(nai)) {
4332 return;
4333 }
4334
4335 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4336 if (VDBG) log("NetworkAgent registered");
4337 } else {
4338 loge("Error connecting NetworkAgent");
4339 mNetworkAgentInfos.remove(nai);
4340 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004341 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004342 synchronized (mNetworkForNetId) {
4343 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004344 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004345 mNetIdManager.releaseNetId(nai.network.getNetId());
4346 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004347 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004348 }
4349 }
4350 }
Paul Jensend5f53392014-11-25 15:26:53 -05004351
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004352 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004353 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004354 }
4355
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004356 @VisibleForTesting
4357 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004358 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004359 if (SdkLevel.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004360
4361 // If the network never roamed, return false. The check below is not sufficient if time
4362 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4363 if (nai.lastRoamTime == 0) return false;
4364
he_won.hwang881307a2022-03-15 21:23:52 +09004365 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4366 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004367 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004368 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004369 final long currentTimeMs = SystemClock.elapsedRealtime();
4370 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004371 if (timeSinceLastRoam <= blockTimeOut) {
4372 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4373 return true;
4374 }
4375 }
4376 return false;
4377 }
4378
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004379 private void handleNetworkAgentDisconnected(Message msg) {
4380 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004381 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004382 }
4383
Chalard Jeand9fffc32018-05-11 20:19:20 +09004384 // Destroys a network, remove references to it from the internal state managed by
4385 // ConnectivityService, free its interfaces and clean up.
4386 // Must be called on the Handler thread.
4387 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004388 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004389
4390 if (!mNetworkAgentInfos.contains(nai)) return;
4391
Chalard Jeand9fffc32018-05-11 20:19:20 +09004392 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004393 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004394 }
lucaslinb25c9a62019-02-12 15:30:13 +08004395 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004396 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004397 // A network agent has disconnected.
4398 // TODO - if we move the logic to the network agent (have them disconnect
4399 // because they lost all their requests or because their score isn't good)
4400 // then they would disconnect organically, report their new state and then
4401 // disconnect the channel.
4402 if (nai.networkInfo.isConnected()) {
4403 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4404 null, null);
4405 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004406 final boolean wasDefault = isDefaultNetwork(nai);
4407 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004408 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004409 }
4410 notifyIfacesChangedForNetworkStats();
4411 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4412 // by other networks that are already connected. Perhaps that can be done by
4413 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4414 // of rematchAllNetworksAndRequests
4415 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004416 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004417
4418 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004419 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4420 // Disable wakeup packet monitoring for each interface.
4421 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4422 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004423 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004424 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004425 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004426 synchronized (mNetworkForNetId) {
4427 // Remove the NetworkAgent, but don't mark the netId as
4428 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004429 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004430 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004431 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004432 // Update allowed network lists in netd. This should be called after removing nai
4433 // from mNetworkAgentInfos.
4434 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004435 // Remove all previously satisfied requests.
4436 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004437 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004438 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004439 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004440 if (currentNetwork != null
4441 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004442 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004443 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4444 // rematch not to keep disconnected agents instead of setting it here ; this
4445 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004446 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004447 for (final NetworkOfferInfo noi : mNetworkOffers) {
4448 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004449 }
James Mattise3ef1912020-12-20 11:09:58 -08004450
Chalard Jean5b409c72021-02-04 13:12:59 +09004451 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004452 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004453 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004454 // network, because while incorrect this is the closest to the old (also
4455 // incorrect) behavior.
4456 mNetworkActivityTracker.updateDataActivityTracking(
4457 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004458 ensureNetworkTransitionWakelock(nai.toShortString());
4459 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004460 }
4461 }
junyulai2b6f0c22021-02-03 20:15:30 +08004462 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004463 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004464 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004465 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004466 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004467 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004468 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004469
4470 // Immediate teardown.
4471 if (nai.teardownDelayMs == 0) {
4472 destroyNetwork(nai);
4473 return;
4474 }
4475
4476 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004477 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304478 try {
4479 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4480 } catch (RemoteException e) {
4481 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4482 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004483 }
4484 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4485 }
4486
4487 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004488 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004489 // Tell netd to clean up the configuration for this network
4490 // (routing rules, DNS, etc).
4491 // This may be slow as it requires a lot of netd shelling out to ip and
4492 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004493 // after we've rematched networks with requests (which might change the default
4494 // network or service a new request from an app), so network traffic isn't interrupted
4495 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004496 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004497 }
Chalard Jean254bd162022-08-25 13:04:51 +09004498 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004499 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4500 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4501 // false if the network was never created.
4502 // TODO: delete when S is no longer supported.
4503 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004504 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004505 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004506 }
4507
Ken Chen6df7a902021-04-09 15:08:42 +08004508 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004509 try {
4510 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004511 final NativeNetworkConfig config;
4512 if (nai.isVPN()) {
4513 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004514 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004515 return false;
4516 }
4517 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4518 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004519 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004520 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004521 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004522 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004523 getNetworkPermission(nai.networkCapabilities),
4524 false /* secure */,
4525 VpnManager.TYPE_VPN_NONE,
4526 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004527 }
Ken Chen6df7a902021-04-09 15:08:42 +08004528 mNetd.networkCreate(config);
4529 mDnsResolver.createNetworkCache(nai.network.getNetId());
4530 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4531 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004532 return true;
4533 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004534 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004535 return false;
4536 }
4537 }
4538
Ken Chen6df7a902021-04-09 15:08:42 +08004539 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004540 if (mDscpPolicyTracker != null) {
4541 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4542 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004543 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004544 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004545 } catch (RemoteException | ServiceSpecificException e) {
4546 loge("Exception destroying network(networkDestroy): " + e);
4547 }
4548 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004549 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004550 } catch (RemoteException | ServiceSpecificException e) {
4551 loge("Exception destroying network: " + e);
4552 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004553 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4554 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4555 // gets created, could add data to DnsManager data structures that will never get deleted.
4556 mDnsManager.removeNetwork(nai.network);
4557
4558 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004559 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004560 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4561 }
4562
Chalard Jean254bd162022-08-25 13:04:51 +09004563 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004564 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004565 }
4566
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004567 // If this method proves to be too slow then we can maintain a separate
4568 // pendingIntent => NetworkRequestInfo map.
4569 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4570 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004571 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4572 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4573 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004574 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004575 return entry.getValue();
4576 }
4577 }
4578 return null;
4579 }
4580
Chalard Jean524f0b12021-10-25 21:11:56 +09004581 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4582 if (SdkLevel.isAtLeastT()) {
4583 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4584 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4585 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4586 // bug is fixed.
4587 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004588 throw new IllegalStateException("This NRI is already registered. New : " + nri
4589 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004590 }
4591 }
4592 }
4593 }
4594
Chalard Jeanac9ace02022-01-26 16:54:05 +09004595 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4596 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004597 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004598 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4599 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004600 }
4601 return false;
4602 }
4603
James Mattisf7027322020-12-13 16:28:14 -08004604 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004605 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004606 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4607 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4608 final NetworkRequestInfo existingRequest =
4609 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004610 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004611 if (DBG) {
4612 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4613 + nri.mRequests.get(0) + " because their intents matched.");
4614 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004615 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004616 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004617 }
Erik Kline05f2b402015-04-30 12:58:40 +09004618 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004619 }
4620
James Mattisf7027322020-12-13 16:28:14 -08004621 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004622 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004623 }
4624
James Mattis3ce3d3c2021-02-09 18:18:28 -08004625 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004626 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004627 for (final NetworkRequestInfo nri : nris) {
4628 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004629 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004630 for (final NetworkRequest req : nri.mRequests) {
4631 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004632 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004633 if (req.isListen()) {
4634 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4635 if (req.networkCapabilities.hasSignalStrength()
4636 && network.satisfiesImmutableCapabilitiesOf(req)) {
4637 updateSignalStrengthThresholds(network, "REGISTER", req);
4638 }
James Mattisf7027322020-12-13 16:28:14 -08004639 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004640 }
4641 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004642
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004643 // If this NRI has a satisfier already, it is replacing an older request that
4644 // has been removed. Track it.
4645 final NetworkRequest activeRequest = nri.getActiveRequest();
4646 if (null != activeRequest) {
4647 // If there is an active request, then for sure there is a satisfier.
4648 nri.getSatisfier().addRequest(activeRequest);
4649 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004650 }
James Mattisf7027322020-12-13 16:28:14 -08004651
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004652 if (mFlags.noRematchAllRequestsOnRegister()) {
4653 rematchNetworksAndRequests(nris);
4654 } else {
4655 rematchAllNetworksAndRequests();
4656 }
James Mattis45d81842021-01-10 14:24:24 -08004657
Chalard Jean0354d8c2021-01-12 10:58:56 +09004658 // Requests that have not been matched to a network will not have been sent to the
4659 // providers, because the old satisfier and the new satisfier are the same (null in this
4660 // case). Send these requests to the providers.
4661 for (final NetworkRequestInfo nri : nris) {
4662 for (final NetworkOfferInfo noi : mNetworkOffers) {
4663 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004664 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004665 }
4666 }
4667
James Mattisf7027322020-12-13 16:28:14 -08004668 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4669 final int callingUid) {
4670 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004671 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004672 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4673 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4674 handleReleaseNetworkRequest(
4675 nri.mRequests.get(0),
4676 callingUid,
4677 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004678 }
4679 }
4680
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004681 // Determines whether the network is the best (or could become the best, if it validated), for
4682 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4683 // on the value of reason:
4684 //
4685 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4686 // then it should be torn down.
4687 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4688 // then it should be lingered.
4689 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004690 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004691
Chalard Jean254bd162022-08-25 13:04:51 +09004692 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004693 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4694 return false;
4695 }
4696
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004697 final int numRequests;
4698 switch (reason) {
4699 case TEARDOWN:
4700 numRequests = nai.numRequestNetworkRequests();
4701 break;
4702 case LINGER:
4703 numRequests = nai.numForegroundNetworkRequests();
4704 break;
4705 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004706 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004707 return true;
4708 }
4709
Chalard Jean947acd42021-03-08 22:29:27 +09004710 if (numRequests > 0) return false;
4711
Paul Jensende49eb12015-06-25 15:30:08 -04004712 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004713 if (reason == UnneededFor.LINGER
4714 && !nri.isMultilayerRequest()
4715 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004716 // Background requests don't affect lingering.
4717 continue;
4718 }
4719
James Mattis3d229892020-11-16 16:46:28 -08004720 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004721 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004722 }
4723 }
Paul Jensende49eb12015-06-25 15:30:08 -04004724 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004725 }
4726
James Mattis3d229892020-11-16 16:46:28 -08004727 private boolean isNetworkPotentialSatisfier(
4728 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4729 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004730 // request, return immediately. For multilayer requests, check to see if any of the
4731 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004732 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4733 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004734 return false;
4735 }
4736 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004737 // This multilayer listen request is satisfied therefore no further requests need to be
4738 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004739 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004740 return false;
4741 }
James Mattis3d229892020-11-16 16:46:28 -08004742 // As non-multilayer listen requests have already returned, the below would only happen
4743 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004744 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004745 continue;
4746 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004747 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004748 // there is hope for it to become one if it validated, then it is needed.
4749 if (candidate.satisfies(req)) {
4750 // As soon as a network is found that satisfies a request, return. Specifically for
4751 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4752 // is important so as to not evaluate lower priority requests further in
4753 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004754 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4755 ? nri.getSatisfier() : null;
4756 // Note that this catches two important cases:
4757 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4758 // is currently satisfying the request. This is desirable when
4759 // cellular ends up validating but WiFi does not.
4760 // 2. Unvalidated WiFi will not be reaped when validated cellular
4761 // is currently satisfying the request. This is desirable when
4762 // WiFi ends up validating and out scoring cellular.
4763 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004764 }
4765 }
4766
4767 return false;
4768 }
4769
Erik Kline0c04b742016-07-07 16:50:58 +09004770 private NetworkRequestInfo getNriForAppRequest(
4771 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004772 // Looking up the app passed param request in mRequests isn't possible since it may return
4773 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4774 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004775 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4776 // to avoid potential race conditions when validating a package->uid mapping when sending
4777 // the callback on the very low-chance that an application shuts down prior to the callback
4778 // being sent.
4779 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4780 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004781
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004782 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004783 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004784 log(String.format("UID %d attempted to %s for unowned request %s",
4785 callingUid, requestedOperation, nri));
4786 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004787 }
Erik Kline0c04b742016-07-07 16:50:58 +09004788 }
4789
4790 return nri;
4791 }
4792
James Mattisf7027322020-12-13 16:28:14 -08004793 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4794 final String callingMethod) {
4795 if (nri.isMultilayerRequest()) {
4796 throw new IllegalStateException(
4797 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004798 }
4799 }
4800
James Mattisf7027322020-12-13 16:28:14 -08004801 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004802 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004803 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4804 // single NetworkRequest and thus does not apply to multilayer requests.
4805 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4806 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004807 return;
4808 }
James Mattis2516da32021-01-31 17:06:19 -08004809 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004810 return;
4811 }
James Mattisf7027322020-12-13 16:28:14 -08004812 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4813 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004814 }
4815 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004816 callCallbackForRequest(
4817 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004818 }
4819
James Mattisf7027322020-12-13 16:28:14 -08004820 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4821 final int callingUid,
4822 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004823 final NetworkRequestInfo nri =
4824 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4825 if (nri == null) {
4826 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004827 }
James Mattisf7027322020-12-13 16:28:14 -08004828 if (VDBG || (DBG && request.isRequest())) {
4829 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004830 }
4831 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004832 if (callOnUnavailable) {
4833 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4834 }
Erik Kline155a59a2015-11-25 12:49:38 +09004835 }
Erik Kline0c04b742016-07-07 16:50:58 +09004836
James Mattisa076c532020-12-02 14:12:41 -08004837 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004838 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004839 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004840 if (null == mNetworkRequests.remove(req)) {
4841 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4842 continue;
4843 }
James Mattisa076c532020-12-02 14:12:41 -08004844 if (req.isListen()) {
4845 removeListenRequestFromNetworks(req);
4846 }
4847 }
James Mattis8f036802021-06-20 16:26:01 -07004848 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004849 if (mDefaultNetworkRequests.remove(nri)) {
4850 // If this request was one of the defaults, then the UID rules need to be updated
4851 // WARNING : if the app(s) for which this network request is the default are doing
4852 // traffic, this will kill their connected sockets, even if an equivalent request
4853 // is going to be reinstated right away ; unconnected traffic will go on the default
4854 // until the new default is set, which will happen very soon.
4855 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4856 // remove ranges for those requests that won't have a replacement
4857 final NetworkAgentInfo satisfier = nri.getSatisfier();
4858 if (null != satisfier) {
4859 try {
paulhu0e79d952021-06-09 16:11:35 +08004860 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4861 satisfier.network.getNetId(),
4862 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004863 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004864 } catch (RemoteException e) {
4865 loge("Exception setting network preference default network", e);
4866 }
4867 }
4868 }
Junyu Lai35665cc2022-12-19 17:37:48 +08004869
Junyu Lai00d92df2022-07-05 11:01:52 +08004870 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004871 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004872 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004873
4874 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004875 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004876 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004877 }
4878 }
4879
Chalard Jean0354d8c2021-01-12 10:58:56 +09004880 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4881 // needed for this offer.
4882 for (final NetworkOfferInfo noi : mNetworkOffers) {
4883 for (final NetworkRequest req : nri.mRequests) {
4884 if (req.isRequest() && noi.offer.neededFor(req)) {
4885 noi.offer.onNetworkUnneeded(req);
4886 }
4887 }
4888 }
James Mattisa076c532020-12-02 14:12:41 -08004889 }
4890
James Mattis3ce3d3c2021-02-09 18:18:28 -08004891 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4892 for (final NetworkRequestInfo nri : nris) {
4893 if (mDefaultRequest == nri) {
4894 // Make sure we never remove the default request.
4895 continue;
4896 }
4897 handleRemoveNetworkRequest(nri);
4898 }
4899 }
4900
James Mattisa076c532020-12-02 14:12:41 -08004901 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4902 // listens don't have a singular affected Network. Check all networks to see
4903 // if this listen request applies and remove it.
4904 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4905 nai.removeRequest(req.requestId);
4906 if (req.networkCapabilities.hasSignalStrength()
4907 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4908 updateSignalStrengthThresholds(nai, "RELEASE", req);
4909 }
4910 }
4911 }
4912
4913 /**
4914 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4915 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4916 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4917 */
4918 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4919 boolean wasKept = false;
4920 final NetworkAgentInfo nai = nri.getSatisfier();
4921 if (nai != null) {
4922 final int requestLegacyType = nri.getActiveRequest().legacyType;
4923 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4924 nai.removeRequest(nri.getActiveRequest().requestId);
4925 if (VDBG || DDBG) {
4926 log(" Removing from current network " + nai.toShortString()
4927 + ", leaving " + nai.numNetworkRequests() + " requests.");
4928 }
4929 // If there are still lingered requests on this network, don't tear it down,
4930 // but resume lingering instead.
4931 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004932 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004933 notifyNetworkLosing(nai, now);
4934 }
4935 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4936 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4937 teardownUnneededNetwork(nai);
4938 } else {
4939 wasKept = true;
4940 }
James Mattisa076c532020-12-02 14:12:41 -08004941 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4942 // Went from foreground to background.
4943 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004944 }
4945
Erik Kline0c04b742016-07-07 16:50:58 +09004946 // Maintain the illusion. When this request arrived, we might have pretended
4947 // that a network connected to serve it, even though the network was already
4948 // connected. Now that this request has gone away, we might have to pretend
4949 // that the network disconnected. LegacyTypeTracker will generate that
4950 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004951 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004952 boolean doRemove = true;
4953 if (wasKept) {
4954 // check if any of the remaining requests for this network are for the
4955 // same legacy type - if so, don't remove the nai
4956 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4957 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004958 if (otherRequest.legacyType == requestLegacyType
4959 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004960 if (DBG) log(" still have other legacy request - leaving");
4961 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004962 }
4963 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004964 }
4965
Erik Kline0c04b742016-07-07 16:50:58 +09004966 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004967 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004968 }
4969 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004970 }
4971 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004972
Junyu Lai00d92df2022-07-05 11:01:52 +08004973 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004974 return checkAnyPermissionOf(
4975 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4976 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4977 }
4978
Lorenzo Colittid6459092016-07-04 12:55:44 +09004979 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004980 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004981 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004982 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004983 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004984 }
4985
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004986 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004987 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4988 enforceNetworkStackSettingsOrSetup();
4989 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4990 encodeBool(accept), encodeBool(always), network));
4991 }
4992
4993 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004994 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004995 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004996 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4997 }
4998
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004999 @Override
5000 public void setTestAllowBadWifiUntil(long timeMs) {
5001 enforceSettingsPermission();
5002 if (!Build.isDebuggable()) {
5003 throw new IllegalStateException("Does not support in non-debuggable build");
5004 }
5005
5006 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5007 throw new IllegalArgumentException("It should not exceed "
5008 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5009 }
5010
5011 mHandler.sendMessage(
5012 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5013 }
5014
chiachangwange0192a72023-02-06 13:25:01 +00005015 @Override
5016 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5017 enforceSettingsPermission();
5018 if (!Build.isDebuggable()) {
5019 throw new IllegalStateException("Is not supported in non-debuggable build");
5020 }
5021
5022 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5023 throw new IllegalArgumentException("Argument should not exceed "
5024 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5025 }
5026
5027 mHandler.sendMessage(
5028 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5029 }
5030
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005031 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5032 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5033 " accept=" + accept + " always=" + always);
5034
5035 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5036 if (nai == null) {
5037 // Nothing to do.
5038 return;
5039 }
5040
Chalard Jean254bd162022-08-25 13:04:51 +09005041 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005042 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005043 return;
5044 }
5045
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005046 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005047 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005048 }
5049
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005050 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5051 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005052 // If network becomes partial connectivity and user already accepted to use this
5053 // network, we should respect the user's option and don't need to popup the
5054 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005055 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005056 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005057 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005058 }
5059
5060 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005061 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005062 }
5063
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005064 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005065 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005066 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005067 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005068 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005069 }
5070
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005071 }
5072
lucaslin2240ef62019-03-12 13:08:03 +08005073 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5074 boolean always) {
5075 if (DBG) {
5076 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5077 + " always=" + always);
5078 }
5079
5080 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5081 if (nai == null) {
5082 // Nothing to do.
5083 return;
5084 }
5085
Chalard Jean254bd162022-08-25 13:04:51 +09005086 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005087 // The network validated while the dialog box was up. Take no action.
5088 return;
5089 }
5090
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005091 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5092 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005093 }
5094
5095 // TODO: Use the current design or save the user choice into IpMemoryStore.
5096 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005097 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005098 }
5099
5100 if (!accept) {
5101 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005102 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005103 // Tear down the network.
5104 teardownUnneededNetwork(nai);
5105 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005106 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5107 // result in a partial connectivity result which will be processed by
5108 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005109 //
5110 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5111 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005112 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005113 }
5114 }
5115
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005116 private void handleSetAvoidUnvalidated(Network network) {
5117 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005118 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005119 // Nothing to do. The network either disconnected or revalidated.
5120 return;
5121 }
Chalard Jean254bd162022-08-25 13:04:51 +09005122 if (0L == nai.getAvoidUnvalidated()) {
5123 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005124 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005125 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005126 }
5127 }
5128
Chalard Jean5fb43c72022-09-08 19:03:14 +09005129 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005130 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005131 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005132 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09005133 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005134 }
5135
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005136 @Override
5137 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005138 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005139 mHandler.post(() -> {
5140 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5141 if (nai == null) return;
5142 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005143 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005144 });
5145 }
5146
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005147 /**
5148 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5149 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005150 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005151 * @param appExtras Bundle to use as intent extras for the captive portal application.
5152 * Must be treated as opaque to avoid preventing the captive portal app to
5153 * update its arguments.
5154 */
5155 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005156 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005157 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5158 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005159
5160 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5161 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005162 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5163 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005164 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5165
lucaslin75ff7022020-12-17 04:14:35 +08005166 final long token = Binder.clearCallingIdentity();
5167 try {
5168 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5169 } finally {
5170 Binder.restoreCallingIdentity(token);
5171 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005172 }
5173
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005174 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5175 private final Network mNetwork;
5176
5177 private CaptivePortalImpl(Network network) {
5178 mNetwork = network;
5179 }
5180
5181 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005182 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005183 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5184 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005185 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5186 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5187 // Since the network will be disconnected, skip notifying NetworkMonitor
5188 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005189 }
5190
Chiachang Wang938bfba2020-01-09 13:50:55 +08005191 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005192 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005193 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005194 }
5195
5196 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005197 public void appRequest(final int request) {
5198 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5199 if (nm == null) return;
5200
5201 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005202 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005203 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005204 }
5205 }
5206
5207 @Nullable
5208 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5209 // getNetworkAgentInfoForNetwork is thread-safe
5210 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5211 if (nai == null) return null;
5212
5213 // nai.networkMonitor() is thread-safe
5214 return nai.networkMonitor();
5215 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005216 }
5217
Hugo Benichic9048bc2016-09-14 23:23:08 +00005218 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005219 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005220 }
5221
Chalard Jean020b93a2022-09-01 13:20:14 +09005222 private boolean activelyPreferBadWifi() {
5223 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5224 }
5225
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005226 /**
5227 * Return whether the device should maintain continuous, working connectivity by switching away
5228 * from WiFi networks having no connectivity.
5229 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5230 */
5231 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005232 if (!checkNetworkStackPermission()) {
5233 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5234 }
5235 return avoidBadWifi();
5236 }
5237
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005238 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005239 ensureRunningOnConnectivityServiceThread();
5240 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005241 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005242 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005243 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005244 if (avoidBadWifi) {
5245 // If the device is now avoiding bad wifi, remove notifications that might have
5246 // been put up when the device didn't.
5247 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5248 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005249 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005250 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5251 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5252 for (final NetworkOfferInfo noi : offersToUpdate) {
5253 updateOfferScore(noi.offer);
5254 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005255 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005256 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005257 }
5258
Erik Kline95ecfee2016-10-02 18:02:14 +09005259 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005260 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005261 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005262 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005263 if (!configRestrict) {
5264 pw.println("Bad Wi-Fi avoidance: unrestricted");
5265 return;
5266 }
5267
5268 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5269 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005270 pw.println("Config restrict: " + configRestrict);
5271 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005272
Chalard Jeane0fdea32022-09-14 21:44:22 +09005273 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005274 String description;
5275 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005276 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005277 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005278 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005279 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005280 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005281 description = "avoid";
5282 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005283 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005284 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005285 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005286
5287 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5288 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005289 if (null == configValue) {
5290 description = "unset";
5291 } else if (configValue) {
5292 description = "force true";
5293 } else {
5294 description = "force false";
5295 }
5296 pw.println("Actively prefer bad wifi conf: " + description);
5297 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005298 pw.println("Network overrides:");
5299 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005300 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005301 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005302 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005303 }
5304 }
5305 pw.decreaseIndent();
5306 pw.decreaseIndent();
5307 }
5308
paulhu7746e4e2020-06-09 19:07:03 +08005309 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5310 // unify the method.
5311 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5312 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5313 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5314 return settingsComponent != null
5315 ? settingsComponent.getPackageName() : "com.android.settings";
5316 }
5317
lucaslinb1e8e382019-01-24 15:55:30 +08005318 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005319 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005320 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005321 switch (type) {
5322 case NO_INTERNET:
5323 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005324 // High priority because it is only displayed for explicitly selected networks.
5325 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005326 break;
lucasline117e2e2019-10-22 18:27:33 +08005327 case PRIVATE_DNS_BROKEN:
5328 action = Settings.ACTION_WIRELESS_SETTINGS;
5329 // High priority because we should let user know why there is no internet.
5330 highPriority = true;
5331 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005332 case LOST_INTERNET:
5333 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005334 // High priority because it could help the user avoid unexpected data usage.
5335 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005336 break;
lucaslin2240ef62019-03-12 13:08:03 +08005337 case PARTIAL_CONNECTIVITY:
5338 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005339 // Don't bother the user with a high-priority notification if the network was not
5340 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005341 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005342 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005343 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005344 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005345 return;
5346 }
5347
5348 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005349 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005350 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005351 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005352 // Some OEMs have their own Settings package. Thus, need to get the current using
5353 // Settings package name instead of just use default name "com.android.settings".
5354 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5355 intent.setClassName(settingsPkgName,
5356 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005357 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005358
paulhu2af50222020-10-11 22:52:27 +08005359 PendingIntent pendingIntent = PendingIntent.getActivity(
5360 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005361 0 /* requestCode */,
5362 intent,
paulhu2af50222020-10-11 22:52:27 +08005363 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005364
Serik Beketayevec8ad212020-12-07 22:43:07 -08005365 mNotifier.showNotification(
5366 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005367 }
5368
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005369 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5370 // Don't prompt if the network is validated, and don't prompt on captive portals
5371 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005372 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005373 return false;
5374 }
5375
5376 // If a network has partial connectivity, always prompt unless the user has already accepted
5377 // partial connectivity and selected don't ask again. This ensures that if the device
5378 // automatically connects to a network that has partial Internet access, the user will
5379 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005380 // because we have prompted them.
5381 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005382 return true;
5383 }
5384
5385 // If a network has no Internet access, only prompt if the network was explicitly selected
5386 // and if the user has not already told us to use the network regardless of whether it
5387 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005388 if (nai.networkAgentConfig.explicitlySelected
5389 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005390 return true;
5391 }
5392
5393 return false;
5394 }
5395
Chalard Jean5fb43c72022-09-08 19:03:14 +09005396 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5397 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005398
Chalard Jean5fb43c72022-09-08 19:03:14 +09005399 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5400 if (null == nai) return;
5401
5402 if (nai.setEvaluated()) {
5403 // If setEvaluated() returned true, the network never had any form of connectivity.
5404 // This may have an impact on request matching if bad WiFi avoidance is off and the
5405 // network was found not to have Internet access.
5406 nai.updateScoreForNetworkAgentUpdate();
5407 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005408
5409 // Also, if this is WiFi and it should be preferred actively, now is the time to
5410 // prompt the user that they walked past and connected to a bad WiFi.
5411 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5412 && !avoidBadWifi()
5413 && activelyPreferBadWifi()) {
5414 // The notification will be removed if the network validates or disconnects.
5415 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5416 return;
5417 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005418 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005419
Chalard Jean5fb43c72022-09-08 19:03:14 +09005420 if (!shouldPromptUnvalidated(nai)) return;
5421
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005422 // Stop automatically reconnecting to this network in the future. Automatically connecting
5423 // to a network that provides no or limited connectivity is not useful, because the user
5424 // cannot use that network except through the notification shown by this method, and the
5425 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005426 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005427
Chalard Jean254bd162022-08-25 13:04:51 +09005428 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005429 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005430 } else {
5431 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5432 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005433 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005434
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005435 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5436 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005437 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005438
lucaslin2240ef62019-03-12 13:08:03 +08005439 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5440 return;
5441 }
5442
5443 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005444 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005445 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005446 }
5447
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005448 @Override
5449 public int getMultipathPreference(Network network) {
5450 enforceAccessPermission();
5451
5452 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005453 if (nai != null && nai.networkCapabilities
5454 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005455 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5456 }
5457
Aaron Huang9a57acf2020-12-08 10:03:29 +08005458 final NetworkPolicyManager netPolicyManager =
5459 mContext.getSystemService(NetworkPolicyManager.class);
5460
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005461 final long token = Binder.clearCallingIdentity();
5462 final int networkPreference;
5463 try {
5464 networkPreference = netPolicyManager.getMultipathPreference(network);
5465 } finally {
5466 Binder.restoreCallingIdentity(token);
5467 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005468 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005469 return networkPreference;
5470 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005471 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5472 }
5473
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005474 @Override
5475 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005476 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005477 }
5478
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005479 private class InternalHandler extends Handler {
5480 public InternalHandler(Looper looper) {
5481 super(looper);
5482 }
5483
5484 @Override
5485 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005486 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005487 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005488 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005489 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005490 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005491 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005492 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005493 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005494 break;
5495 }
Jason Monka69f1b02013-10-10 14:02:51 -04005496 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005497 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5498 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005499 break;
5500 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005501 case EVENT_REGISTER_NETWORK_PROVIDER: {
5502 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005503 break;
5504 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005505 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5506 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005507 break;
5508 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005509 case EVENT_REGISTER_NETWORK_OFFER: {
5510 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5511 break;
5512 }
5513 case EVENT_UNREGISTER_NETWORK_OFFER: {
5514 final NetworkOfferInfo offer =
5515 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5516 if (null != offer) {
5517 handleUnregisterNetworkOffer(offer);
5518 }
5519 break;
5520 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005521 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005522 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5523 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5524 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005525 break;
5526 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005527 case EVENT_REGISTER_NETWORK_REQUEST:
5528 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005529 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005530 break;
5531 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005532 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5533 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005534 handleRegisterNetworkRequestWithIntent(msg);
5535 break;
5536 }
Erik Kline155a59a2015-11-25 12:49:38 +09005537 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5538 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5539 handleTimedOutNetworkRequest(nri);
5540 break;
5541 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005542 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5543 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5544 break;
5545 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005546 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005547 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5548 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005549 break;
5550 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005551 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005552 Network network = (Network) msg.obj;
5553 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005554 break;
5555 }
lucaslin2240ef62019-03-12 13:08:03 +08005556 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5557 Network network = (Network) msg.obj;
5558 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5559 toBool(msg.arg2));
5560 break;
5561 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005562 case EVENT_SET_AVOID_UNVALIDATED: {
5563 handleSetAvoidUnvalidated((Network) msg.obj);
5564 break;
5565 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005566 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5567 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005568 break;
5569 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005570 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5571 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005572 break;
5573 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005574 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005575 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005576 mKeepaliveTracker.handleStartKeepalive(msg);
5577 break;
5578 }
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005579 case NetworkAgent.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09005580 final AutomaticOnOffKeepalive ki =
5581 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
5582 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005583
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005584 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005585 boolean networkFound = false;
5586 final ArrayList<NetworkAgentInfo> vpnsRunningOnThisNetwork = new ArrayList<>();
5587 for (NetworkAgentInfo n : mNetworkAgentInfos) {
5588 if (n.network.equals(network)) networkFound = true;
5589 if (n.isVPN() && n.everConnected() && hasUnderlyingNetwork(n, network)) {
5590 vpnsRunningOnThisNetwork.add(n);
5591 }
5592 }
5593
5594 // If the network no longer exists, then the keepalive should have been
5595 // cleaned up already. There is no point trying to resume keepalives.
5596 if (!networkFound) return;
5597
5598 if (!vpnsRunningOnThisNetwork.isEmpty()) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005599 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005600 // TODO: check all the VPNs running on top of this network
5601 vpnsRunningOnThisNetwork.get(0).network.netId);
5602 } else {
5603 // If no VPN, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005604 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005605 }
5606 break;
5607 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005608 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005609 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005610 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
5611 (IBinder) msg.obj);
5612 if (ki == null) {
5613 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00005614 return;
5615 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005616 final int reason = msg.arg2;
5617 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005618 break;
5619 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005620 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5621 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5622 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005623 break;
5624 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005625 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5626 handlePrivateDnsSettingsChanged();
5627 break;
dalyk1720e542018-03-05 12:42:22 -05005628 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5629 handlePrivateDnsValidationUpdate(
5630 (PrivateDnsValidationUpdate) msg.obj);
5631 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005632 case EVENT_UID_BLOCKED_REASON_CHANGED:
5633 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005634 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005635 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5636 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5637 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005638 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005639 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5640 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005641 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005642 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005643 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005644 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005645 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5646 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005647 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005648 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005649 }
lucaslin1193a5d2021-01-21 02:04:15 +08005650 case EVENT_REPORT_NETWORK_ACTIVITY:
5651 mNetworkActivityTracker.handleReportNetworkActivity();
5652 break;
paulhu51f77dc2021-06-07 02:34:20 +00005653 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5654 handleMobileDataPreferredUidsChanged();
5655 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005656 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5657 final long timeMs = ((Long) msg.obj).longValue();
5658 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5659 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005660 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5661 handleIngressRateLimitChanged();
5662 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005663 case EVENT_USER_DOES_NOT_WANT:
5664 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5665 if (nai == null) break;
5666 nai.onPreventAutomaticReconnect();
5667 nai.disconnect();
5668 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00005669 case EVENT_SET_VPN_NETWORK_PREFERENCE:
5670 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
5671 break;
chiachangwange0192a72023-02-06 13:25:01 +00005672 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
5673 final long time = ((Long) msg.obj).longValue();
5674 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
5675 break;
5676 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005677 }
5678 }
5679 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005680
Lorenzo Colittid6459092016-07-04 12:55:44 +09005681 @Override
markchien5776f962019-12-16 20:15:20 +08005682 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005683 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005684 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005685 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5686 Context.TETHERING_SERVICE);
5687 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005688 }
5689
Lorenzo Colittid6459092016-07-04 12:55:44 +09005690 @Override
markchien5776f962019-12-16 20:15:20 +08005691 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005692 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005693 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005694 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5695 Context.TETHERING_SERVICE);
5696 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005697 }
5698
Lorenzo Colittid6459092016-07-04 12:55:44 +09005699 @Override
markchien5776f962019-12-16 20:15:20 +08005700 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005701 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005702 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005703 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5704 Context.TETHERING_SERVICE);
5705 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005706 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005707
markchien5776f962019-12-16 20:15:20 +08005708
Lorenzo Colittid6459092016-07-04 12:55:44 +09005709 @Override
markchien5776f962019-12-16 20:15:20 +08005710 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005711 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005712 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005713 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5714 Context.TETHERING_SERVICE);
5715
5716 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005717 }
5718
Lorenzo Colittid6459092016-07-04 12:55:44 +09005719 @Override
markchien5776f962019-12-16 20:15:20 +08005720 @Deprecated
5721 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005722 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005723 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5724 Context.TETHERING_SERVICE);
5725
5726 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005727 }
5728
Udam Saini8f7d6a72017-06-07 12:06:28 -07005729 @Override
markchien5776f962019-12-16 20:15:20 +08005730 @Deprecated
5731 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005732 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005733 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5734 Context.TETHERING_SERVICE);
5735 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005736 }
5737
Robert Greenwalte0b00512014-07-02 09:59:16 -07005738 // Called when we lose the default network and have no replacement yet.
5739 // This will automatically be cleared after X seconds or a new default network
5740 // becomes CONNECTED, whichever happens first. The timer is started by the
5741 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005742 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005743 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005744 if (mNetTransitionWakeLock.isHeld()) {
5745 return;
5746 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005747 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005748 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5749 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005750 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005751 mWakelockLogs.log("ACQUIRE for " + forWhom);
5752 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005753 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005754 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005755 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005756 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005757
Hugo Benichi471b62a2017-03-30 23:18:10 +09005758 // Called when we gain a new default network to release the network transition wakelock in a
5759 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5760 // message is cancelled.
5761 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005762 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005763 if (!mNetTransitionWakeLock.isHeld()) {
5764 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005765 }
5766 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005767 // Cancel self timeout on wakelock hold.
5768 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5769 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5770 mHandler.sendMessageDelayed(msg, 1000);
5771 }
5772
5773 // Called when either message of ensureNetworkTransitionWakelock or
5774 // scheduleReleaseNetworkTransitionWakelock is processed.
5775 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5776 String event = eventName(eventId);
5777 synchronized (this) {
5778 if (!mNetTransitionWakeLock.isHeld()) {
5779 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005780 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005781 return;
5782 }
5783 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005784 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5785 mTotalWakelockDurationMs += lockDuration;
5786 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5787 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005788 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005789 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005790 }
5791
Robert Greenwalt986c7412010-09-08 15:24:47 -07005792 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005793 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005794 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005795 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005796 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005797 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005798 }
5799
Lorenzo Colittid6459092016-07-04 12:55:44 +09005800 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005801 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005802 enforceAccessPermission();
5803 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005804 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005805 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005806
5807 final NetworkAgentInfo nai;
5808 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005809 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005810 } else {
5811 nai = getNetworkAgentInfoForNetwork(network);
5812 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005813
5814 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005815 mHandler.obtainMessage(
5816 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005817 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005818
Hugo Benichid6b510a2017-04-06 17:22:18 +09005819 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005820 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005821 if (nai == null
5822 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005823 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005824 return;
5825 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005826 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005827 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005828 mConnectivityDiagnosticsHandler.sendMessage(
5829 mConnectivityDiagnosticsHandler.obtainMessage(
5830 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5831 new ReportedNetworkConnectivityInfo(
5832 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005833 return;
5834 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005835 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005836 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005837 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005838 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005839 // Validating a network that has not yet connected could result in a call to
5840 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005841 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005842 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005843 }
paulhu7aeba372020-12-30 00:42:19 +08005844 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5845 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005846 return;
5847 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005848
5849 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5850 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5851 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5852 // completed.
5853 mConnectivityDiagnosticsHandler.sendMessage(
5854 mConnectivityDiagnosticsHandler.obtainMessage(
5855 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5856 new ReportedNetworkConnectivityInfo(
5857 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005858 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005859 }
5860
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005861 // TODO: call into netd.
5862 private boolean queryUserAccess(int uid, Network network) {
5863 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5864 if (nai == null) return false;
5865
5866 // Any UID can use its default network.
5867 if (nai == getDefaultNetworkForUid(uid)) return true;
5868
5869 // Privileged apps can use any network.
5870 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5871 return true;
5872 }
5873
5874 // An unprivileged UID can use a VPN iff the VPN applies to it.
5875 if (nai.isVPN()) {
5876 return nai.networkCapabilities.appliesToUid(uid);
5877 }
5878
5879 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5880 // sockets, i.e., if it is the owner.
5881 final NetworkAgentInfo vpn = getVpnForUid(uid);
5882 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5883 && uid != vpn.networkCapabilities.getOwnerUid()) {
5884 return false;
5885 }
5886
5887 // The UID's permission must be at least sufficient for the network. Since the restricted
5888 // permission was already checked above, that just leaves background networks.
5889 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5890 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5891 }
5892
5893 // Unrestricted network. Anyone gets to use it.
5894 return true;
5895 }
5896
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005897 /**
5898 * Returns information about the proxy a certain network is using. If given a null network, it
5899 * it will return the proxy for the bound network for the caller app or the default proxy if
5900 * none.
5901 *
5902 * @param network the network we want to get the proxy information for.
5903 * @return Proxy information if a network has a proxy configured, or otherwise null.
5904 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005905 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005906 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005907 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005908 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005909 if (network == null) {
5910 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005911 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005912 true);
5913 if (activeNetwork == null) {
5914 return null;
5915 }
5916 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005917 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005918 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5919 // caller may not have.
5920 return getLinkPropertiesProxyInfo(network);
5921 }
5922 // No proxy info available if the calling UID does not have network access.
5923 return null;
5924 }
5925
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005926
5927 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005928 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5929 if (nai == null) return null;
5930 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005931 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5932 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005933 }
5934 }
5935
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005936 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005937 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005938 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005939 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005940 }
5941
Chalard Jean777e2e52018-06-07 18:02:37 +09005942 @Override
5943 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005944 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005945 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005946 }
5947
Junyu Lai970963e2022-10-25 15:46:47 +08005948 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005949 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005950 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005951 proxy = null;
5952 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005953 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005954 }
5955
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005956 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5957 // when any network changes proxy.
5958 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5959 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08005960 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
5961 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05005962 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5963
Chalard Jean7d97afc2018-06-07 17:41:29 +09005964 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005965 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005966 }
5967 }
5968
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005969 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005970 final private HashMap<Uri, Integer> mUriEventMap;
5971 final private Context mContext;
5972 final private Handler mHandler;
5973
5974 SettingsObserver(Context context, Handler handler) {
5975 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005976 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005977 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005978 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005979 }
5980
Erik Kline05f2b402015-04-30 12:58:40 +09005981 void observe(Uri uri, int what) {
5982 mUriEventMap.put(uri, what);
5983 final ContentResolver resolver = mContext.getContentResolver();
5984 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005985 }
5986
5987 @Override
5988 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005989 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005990 }
5991
5992 @Override
5993 public void onChange(boolean selfChange, Uri uri) {
5994 final Integer what = mUriEventMap.get(uri);
5995 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005996 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005997 } else {
5998 loge("No matching event to send for URI=" + uri);
5999 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006000 }
6001 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006002
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006003 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006004 Log.d(TAG, s);
6005 }
6006
6007 private static void logw(String s) {
6008 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006009 }
6010
Daniel Brightf9e945b2020-06-15 16:10:01 -07006011 private static void logwtf(String s) {
6012 Log.wtf(TAG, s);
6013 }
6014
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006015 private static void logwtf(String s, Throwable t) {
6016 Log.wtf(TAG, s, t);
6017 }
6018
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006019 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006020 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006021 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006022
Hugo Benichi39621362017-02-11 17:04:43 +09006023 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006024 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006025 }
6026
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006027 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006028 * Return the information of all ongoing VPNs.
6029 *
6030 * <p>This method is used to update NetworkStatsService.
6031 *
6032 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006033 */
junyulai2050bed2021-01-23 09:46:34 +08006034 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006035 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006036 if (mLockdownEnabled) {
6037 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006038 }
junyulai2050bed2021-01-23 09:46:34 +08006039 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006040 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006041 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006042 if (info != null) {
6043 infoList.add(info);
6044 }
6045 }
junyulai2050bed2021-01-23 09:46:34 +08006046 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006047 }
6048
6049 /**
6050 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006051 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006052 */
junyulai2050bed2021-01-23 09:46:34 +08006053 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006054 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006055 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6056 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006057 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6058 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6059 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006060 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6061 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006062 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006063 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006064 }
6065 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006066
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006067 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006068
6069 List<String> interfaces = new ArrayList<>();
6070 for (Network network : underlyingNetworks) {
6071 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6072 if (underlyingNai == null) continue;
6073 LinkProperties lp = underlyingNai.linkProperties;
6074 for (String iface : lp.getAllInterfaceNames()) {
6075 if (!TextUtils.isEmpty(iface)) {
6076 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006077 }
6078 }
Benedict Wong34857f82019-06-12 17:46:15 +00006079 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006080
6081 if (interfaces.isEmpty()) return null;
6082
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006083 // Must be non-null or NetworkStatsService will crash.
6084 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6085 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006086 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006087 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006088
junyulai2050bed2021-01-23 09:46:34 +08006089 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6090 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006091 }
6092
James Mattisd31bdfa2020-12-23 16:37:26 -08006093 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006094 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6095 Network[] underlyingNetworks) {
6096 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006097 if (underlyingNetworks == null && defaultNetwork != null) {
6098 // null underlying networks means to track the default.
6099 underlyingNetworks = new Network[] { defaultNetwork };
6100 }
6101 return underlyingNetworks;
6102 }
6103
6104 // Returns true iff |network| is an underlying network of |nai|.
6105 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6106 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6107 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006108 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006109 final Network[] underlying = underlyingNetworksOrDefault(
6110 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006111 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006112 }
6113
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006114 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006115 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006116 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006117 * When underlying networks change, such networks may have to update capabilities to reflect
6118 * things like the metered bit, their transports, and so on. The capabilities are calculated
6119 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006120 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006121 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006122 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006123 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006124 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006125 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006126 }
6127 }
6128 }
6129
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006130 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6131 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6132 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6133 // a VPN is not up.
6134 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6135 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6136 for (UidRange range : blockedUidRanges) {
6137 if (range.contains(uid)) return true;
6138 }
6139 return false;
6140 }
6141
6142 @Override
6143 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006144 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006145 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6146 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6147 }
6148
6149 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6150 if (DBG) {
6151 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6152 + Arrays.toString(ranges));
6153 }
6154 // Cannot use a Set since the list of UID ranges might contain duplicates.
6155 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6156 for (int i = 0; i < ranges.length; i++) {
6157 if (requireVpn) {
6158 newVpnBlockedUidRanges.add(ranges[i]);
6159 } else {
6160 newVpnBlockedUidRanges.remove(ranges[i]);
6161 }
6162 }
6163
6164 try {
6165 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6166 } catch (RemoteException | ServiceSpecificException e) {
6167 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6168 + Arrays.toString(ranges) + "): netd command failed: " + e);
6169 }
6170
Motomu Utsumib08654c2022-05-11 05:56:26 +00006171 if (SdkLevel.isAtLeastT()) {
6172 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6173 }
6174
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006175 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6176 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006177 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6178 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006179 }
6180
6181 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6182 }
6183
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006184 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006185 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006186 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006187 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006188 }
6189
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006190 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6191 return mLockdownEnabled
6192 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6193 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006194 }
6195
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006196 private NetworkAgentInfo getLegacyLockdownNai() {
6197 if (!mLockdownEnabled) {
6198 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006199 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006200 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006201 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6202 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006203
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006204 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006205 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6206 // a local variable. There is no need to make a copy because its contents cannot change.
6207 final Network[] underlying = nai.declaredUnderlyingNetworks;
6208 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006209 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006210 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006211
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006212 // The legacy lockdown VPN always uses the default network.
6213 // If the VPN's underlying network is no longer the current default network, it means that
6214 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006215 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6216 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006217 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006218 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006219 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006220 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006221
6222 return nai;
6223 };
6224
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006225 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6226 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6227 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006228 private DetailedState getLegacyLockdownState(DetailedState origState) {
6229 if (origState != DetailedState.CONNECTED) {
6230 return origState;
6231 }
6232 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6233 ? DetailedState.CONNECTING
6234 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006235 }
6236
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006237 private void filterForLegacyLockdown(NetworkInfo ni) {
6238 if (!mLockdownEnabled || !ni.isConnected()) return;
6239 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6240 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6241 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6242 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6243 // network, this time with a state of CONNECTED.
6244 //
6245 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6246 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6247 // is not too far off the truth, since an always-on VPN, when not connected, is always
6248 // trying to reconnect.
6249 if (getLegacyLockdownNai() == null) {
6250 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6251 }
6252 }
6253
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006254 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006255 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006256 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006257 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006258 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6259 return;
6260 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006261 final long ident = Binder.clearCallingIdentity();
6262 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006263 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006264 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006265 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006266 } finally {
6267 Binder.restoreCallingIdentity(ident);
6268 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006269 }
Wink Savillecb117d32013-08-29 14:57:08 -07006270
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006271 @Override
6272 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006273 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006274 final long ident = Binder.clearCallingIdentity();
6275 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006276 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006277 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006278 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6279 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006280 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006281 } finally {
6282 Binder.restoreCallingIdentity(ident);
6283 }
6284 }
6285
James Mattis02220e22021-03-13 19:27:21 -08006286 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006287 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6288 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6289 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006290 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006291 }
6292
James Mattis02220e22021-03-13 19:27:21 -08006293 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006294 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006295 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006296 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6297 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006298 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006299 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6300 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6301 }
junyulaid91e7052020-08-28 13:44:33 +08006302 }
6303
James Mattis02220e22021-03-13 19:27:21 -08006304 private void onPackageChanged(@NonNull final String packageName) {
6305 // This is necessary in case a package is added or removed, but also when it's replaced to
6306 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6307 // as one in the preferences, then it should follow the same routing as that other package,
6308 // which means updating the rules is never to be needed in this case (whether it joins or
6309 // leaves a UID with a preference).
6310 if (isMappedInOemNetworkPreference(packageName)) {
6311 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6312 }
6313 }
6314
6315 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006316 @Override
6317 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006318 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006319 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006320 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006321
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006322 // User should be filled for below intents, check the existence.
6323 if (user == null) {
6324 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6325 return;
6326 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006327
Lorenzo Colitticd675292021-02-04 17:32:07 +09006328 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006329 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006330 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006331 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006332 } else {
junyulaid91e7052020-08-28 13:44:33 +08006333 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006334 }
6335 }
6336 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006337
James Mattis02220e22021-03-13 19:27:21 -08006338 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6339 @Override
6340 public void onReceive(Context context, Intent intent) {
6341 ensureRunningOnConnectivityServiceThread();
6342 switch (intent.getAction()) {
6343 case Intent.ACTION_PACKAGE_ADDED:
6344 case Intent.ACTION_PACKAGE_REMOVED:
6345 case Intent.ACTION_PACKAGE_REPLACED:
6346 onPackageChanged(intent.getData().getSchemeSpecificPart());
6347 break;
6348 default:
6349 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6350 }
6351 }
6352 };
6353
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006354 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006355 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006356
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006357 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006358 public final String name;
6359 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006360 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006361 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006362
lifraf3a3492021-03-10 13:58:14 +08006363 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6364 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006365 this.name = name;
6366 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006367 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006368 mDeathRecipient = deathRecipient;
6369
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006370 if (mDeathRecipient == null) {
6371 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006372 }
6373 }
6374
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006375 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006376 try {
6377 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6378 } catch (RemoteException e) {
6379 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006380 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006381 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006382 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006383
James Mattis4fce5d12020-11-12 15:53:42 -08006384 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6385 for (int i = 0; i < requests.size(); i++) {
6386 ensureNetworkRequestHasType(requests.get(i));
6387 }
6388 }
6389
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006390 private void ensureNetworkRequestHasType(NetworkRequest request) {
6391 if (request.type == NetworkRequest.Type.NONE) {
6392 throw new IllegalArgumentException(
6393 "All NetworkRequests in ConnectivityService must have a type");
6394 }
6395 }
6396
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006397 /**
6398 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006399 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006400 */
James Mattis258ea3c2020-11-15 15:04:40 -08006401 @VisibleForTesting
6402 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006403 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6404 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006405 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006406
James Mattisa076c532020-12-02 14:12:41 -08006407 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6408 void setSatisfier(
6409 @Nullable final NetworkAgentInfo satisfier,
6410 @Nullable final NetworkRequest activeRequest) {
6411 mSatisfier = satisfier;
6412 mActiveRequest = activeRequest;
6413 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006414
James Mattisd31bdfa2020-12-23 16:37:26 -08006415 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006416 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006417 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006418 private NetworkAgentInfo mSatisfier;
6419 NetworkAgentInfo getSatisfier() {
6420 return mSatisfier;
6421 }
6422
6423 // The request in mRequests assigned to a network agent. This is null if none of the
6424 // requests in mRequests can be satisfied. This member has the constraint of only being
6425 // accessible on the handler thread.
6426 @Nullable
6427 private NetworkRequest mActiveRequest;
6428 NetworkRequest getActiveRequest() {
6429 return mActiveRequest;
6430 }
6431
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006432 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006433 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006434 @Nullable
6435 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006436
6437 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006438 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006439 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006440 final int mPid;
6441 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006442 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006443 @Nullable
6444 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006445
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006446 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006447 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006448
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006449 // Effective UID of this request. This is different from mUid when a privileged process
6450 // files a request on behalf of another UID. This UID is used to determine blocked status,
6451 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6452 // maximum limit of registered callbacks per UID.
6453 final int mAsUid;
6454
paulhu48291862021-07-14 14:53:57 +08006455 // Preference order of this request.
6456 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006457
James Mattis3ce3d3c2021-02-09 18:18:28 -08006458 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6459 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6460 // maintained for keying off of. This is only a concern when the original nri
6461 // mNetworkRequests changes which happens currently for apps that register callbacks to
6462 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6463 // that match the per-app default nri that currently tracks the calling app's uid so that
6464 // callbacks are fired at the appropriate time. When the callbacks fire,
6465 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6466 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6467 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6468 @NonNull
6469 private final NetworkRequest mNetworkRequestForCallback;
6470 NetworkRequest getNetworkRequestForCallback() {
6471 return mNetworkRequestForCallback;
6472 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006473
James Mattisd31bdfa2020-12-23 16:37:26 -08006474 /**
6475 * Get the list of UIDs this nri applies to.
6476 */
6477 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006478 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006479 // networkCapabilities.getUids() returns a defensive copy.
6480 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006481 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6482 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006483 }
6484
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006485 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6486 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006487 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006488 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006489 }
6490
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006491 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006492 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006493 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006494 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006495 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006496 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006497 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006498 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006499 mBinder = null;
6500 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006501 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006502 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006503 mPerUidCounter = getRequestCounter(this);
6504 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006505 /**
6506 * Location sensitive data not included in pending intent. Only included in
6507 * {@link NetworkCallback}.
6508 */
6509 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006510 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006511 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006512 }
6513
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006514 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006515 @Nullable final IBinder binder,
6516 @NetworkCallback.Flag int callbackFlags,
6517 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006518 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6519 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006520 }
6521
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006522 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006523 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006524 @Nullable final IBinder binder,
6525 @NetworkCallback.Flag int callbackFlags,
6526 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006527 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006528 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006529 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006530 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006531 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006532 mBinder = binder;
6533 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006534 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006535 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006536 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006537 mPerUidCounter = getRequestCounter(this);
6538 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006539 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006540 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006541 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006542 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006543 }
6544
James Mattis3ce3d3c2021-02-09 18:18:28 -08006545 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6546 @NonNull final List<NetworkRequest> r) {
6547 super();
6548 ensureAllNetworkRequestsHaveType(r);
6549 mRequests = initializeRequests(r);
6550 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006551 final NetworkAgentInfo satisfier = nri.getSatisfier();
6552 if (null != satisfier) {
6553 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6554 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006555 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006556 // As this code creates a new NRI with a new set of requests, figure out which of
6557 // the list of requests should be the active request. It is always the first
6558 // request of the list that can be satisfied by the satisfier since the order of
6559 // requests is a priority order.
6560 // Note even in the presence of a satisfier there may not be an active request,
6561 // when the satisfier is the no-service network.
6562 NetworkRequest activeRequest = null;
6563 for (final NetworkRequest candidate : r) {
6564 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6565 activeRequest = candidate;
6566 break;
6567 }
6568 }
6569 setSatisfier(satisfier, activeRequest);
6570 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006571 mMessenger = nri.mMessenger;
6572 mBinder = nri.mBinder;
6573 mPid = nri.mPid;
6574 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006575 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006576 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006577 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006578 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006579 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006580 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006581 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006582 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006583 }
6584
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006585 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006586 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006587 }
6588
paulhue9913722021-05-26 15:19:20 +08006589 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006590 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006591 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006592 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006593 }
6594
James Mattis2516da32021-01-31 17:06:19 -08006595 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6596 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6597 // false.
6598 boolean isBeingSatisfied() {
6599 return (null != mSatisfier && null != mActiveRequest);
6600 }
6601
James Mattis3d229892020-11-16 16:46:28 -08006602 boolean isMultilayerRequest() {
6603 return mRequests.size() > 1;
6604 }
6605
James Mattis45d81842021-01-10 14:24:24 -08006606 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6607 // Creating a defensive copy to prevent the sender from modifying the list being
6608 // reflected in the return value of this method.
6609 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006610 return Collections.unmodifiableList(tempRequests);
6611 }
6612
James Mattisb1392002021-03-31 13:57:52 -07006613 void linkDeathRecipient() {
6614 if (null != mBinder) {
6615 try {
6616 mBinder.linkToDeath(this, 0);
6617 } catch (RemoteException e) {
6618 binderDied();
6619 }
6620 }
6621 }
6622
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006623 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006624 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006625 try {
6626 mBinder.unlinkToDeath(this, 0);
6627 } catch (NoSuchElementException e) {
6628 // Temporary workaround for b/194394697 pending analysis of additional logs
6629 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6630 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006631 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006632 }
6633
paulhu48291862021-07-14 14:53:57 +08006634 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6635 // Compare two preference orders.
6636 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006637 }
6638
paulhu48291862021-07-14 14:53:57 +08006639 int getPreferenceOrderForNetd() {
6640 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6641 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6642 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006643 }
paulhu48291862021-07-14 14:53:57 +08006644 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006645 }
6646
James Mattis4fce5d12020-11-12 15:53:42 -08006647 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006648 public void binderDied() {
6649 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006650 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006651 // As an immutable collection, mRequests cannot change by the time the
6652 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6653 // is acceptable. Use handleReleaseNetworkRequest and not directly
6654 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6655 // the app already unregistered the request.
6656 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6657 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006658 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006659
James Mattis4fce5d12020-11-12 15:53:42 -08006660 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006661 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006662 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6663 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006664 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006665 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006666 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006667 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006668 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006669 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006670 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006671 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006672 }
6673
Junyu Lai00d92df2022-07-05 11:01:52 +08006674 // Keep backward compatibility since the ServiceSpecificException is used by
6675 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6676 public static class RequestInfoPerUidCounter extends PerUidCounter {
6677 RequestInfoPerUidCounter(int maxCountPerUid) {
6678 super(maxCountPerUid);
6679 }
6680
6681 @Override
6682 public synchronized void incrementCountOrThrow(int uid) {
6683 try {
6684 super.incrementCountOrThrow(uid);
6685 } catch (IllegalStateException e) {
6686 throw new ServiceSpecificException(
6687 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6688 "Uid " + uid + " exceeded its allotted requests limit");
6689 }
6690 }
6691
6692 @Override
6693 public synchronized void decrementCountOrThrow(int uid) {
6694 throw new UnsupportedOperationException("Use decrementCount instead.");
6695 }
6696
6697 public synchronized void decrementCount(int uid) {
6698 try {
6699 super.decrementCountOrThrow(uid);
6700 } catch (IllegalStateException e) {
6701 logwtf("Exception when decrement per uid request count: ", e);
6702 }
6703 }
6704 }
6705
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006706 // This checks that the passed capabilities either do not request a
6707 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006708 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006709 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006710 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006711 throw new SecurityException("Insufficient permissions to request a specific SSID");
6712 }
paulhu1a407652019-03-22 16:35:06 +08006713
6714 if (nc.hasSignalStrength()
6715 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6716 throw new SecurityException(
6717 "Insufficient permissions to request a specific signal strength");
6718 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006719 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006720
junyulai2217bec2021-04-14 23:33:31 +08006721 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006722 enforceNetworkFactoryPermission();
6723 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006724 }
6725
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006726 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006727 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006728 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006729 // mNetworkRequests may contain the same value multiple times in case of
6730 // multilayer requests. It won't matter in this case because the thresholds
6731 // will then be the same and be deduplicated as they enter the `thresholds` set.
6732 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006733 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6734 for (final NetworkRequest req : nri.mRequests) {
6735 if (req.networkCapabilities.hasSignalStrength()
6736 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6737 thresholds.add(req.networkCapabilities.getSignalStrength());
6738 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006739 }
6740 }
6741 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006742 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006743 }
6744
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006745 private void updateSignalStrengthThresholds(
6746 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006747 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006748
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006749 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006750 String detail;
6751 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6752 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6753 } else {
6754 detail = reason;
6755 }
6756 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006757 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006758 }
6759
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006760 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006761 }
6762
Chalard Jeandd421992021-12-16 23:16:02 +09006763 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006764 if (nc == null) {
6765 return;
6766 }
6767 NetworkSpecifier ns = nc.getNetworkSpecifier();
6768 if (ns == null) {
6769 return;
6770 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006771 if (ns instanceof MatchAllNetworkSpecifier) {
6772 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6773 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006774 }
6775
Chalard Jeandd421992021-12-16 23:16:02 +09006776 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006777 ensureValidNetworkSpecifier(nc);
6778 if (nc.isPrivateDnsBroken()) {
6779 throw new IllegalArgumentException("Can't request broken private DNS");
6780 }
Chalard Jeande665262022-02-25 16:12:12 +09006781 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006782 throw new IllegalArgumentException("Can't request access UIDs");
6783 }
lucasline117e2e2019-10-22 18:27:33 +08006784 }
6785
Chalard Jeandd421992021-12-16 23:16:02 +09006786 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6787 ensureListenableCapabilities(nc);
6788 final String badCapability = nc.describeFirstNonRequestableCapability();
6789 if (badCapability != null) {
6790 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6791 }
6792 }
6793
Chiachang Wang3bc52762021-11-25 14:17:57 +08006794 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6795 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006796 private boolean isTargetSdkAtleast(int version, int callingUid,
6797 @NonNull String callingPackageName) {
6798 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006799 final PackageManager pm =
6800 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006801 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006802 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006803 if (callingVersion < version) return false;
6804 } catch (PackageManager.NameNotFoundException e) { }
6805 return true;
6806 }
6807
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006808 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006809 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006810 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006811 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006812 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006813 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006814 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6815 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006816 throw new SecurityException("Insufficient permissions to specify legacy type");
6817 }
markchienfac84a22020-03-18 21:16:15 +08006818 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006819 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006820 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006821 // Privileged callers can track the default network of another UID by passing in a UID.
6822 if (asUid != Process.INVALID_UID) {
6823 enforceSettingsPermission();
6824 } else {
6825 asUid = callingUid;
6826 }
junyulaiad010792021-01-11 16:53:38 +08006827 final NetworkRequest.Type reqType;
6828 try {
6829 reqType = NetworkRequest.Type.values()[reqTypeInt];
6830 } catch (ArrayIndexOutOfBoundsException e) {
6831 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6832 }
6833 switch (reqType) {
6834 case TRACK_DEFAULT:
6835 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006836 // is unused and will be replaced by ones appropriate for the UID (usually, the
6837 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006838 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006839 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006840 enforceAccessPermission();
6841 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006842 case TRACK_SYSTEM_DEFAULT:
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08006843 enforceSettingsOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006844 networkCapabilities = new NetworkCapabilities(defaultNc);
6845 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006846 case BACKGROUND_REQUEST:
6847 enforceNetworkStackOrSettingsPermission();
6848 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006849 case REQUEST:
6850 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6851 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006852 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006853 // TODO: this is incorrect. We mark the request as metered or not depending on
6854 // the state of the app when the request is filed, but we never change the
6855 // request if the app changes network state. http://b/29964605
6856 enforceMeteredApnPolicy(networkCapabilities);
6857 break;
junyulai1b1c8742021-03-12 20:05:08 +08006858 case LISTEN_FOR_BEST:
6859 enforceAccessPermission();
6860 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6861 break;
junyulaiad010792021-01-11 16:53:38 +08006862 default:
6863 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006864 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006865 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006866 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006867 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006868
junyulai1b1c8742021-03-12 20:05:08 +08006869 // Enforce FOREGROUND if the caller does not have permission to use background network.
6870 if (reqType == LISTEN_FOR_BEST) {
6871 restrictBackgroundRequestForCaller(networkCapabilities);
6872 }
6873
6874 // Set the UID range for this request to the single UID of the requester, unless the
6875 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006876 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6877 // are no visible methods to set the UIDs, an app could use reflection to try and get
6878 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006879 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006880 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6881 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006882
Etan Cohen85000162017-02-05 10:42:27 -08006883 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006884 throw new IllegalArgumentException("Bad timeout specified");
6885 }
Etan Cohen9786d922015-11-18 10:56:15 -08006886
James Mattis3ce3d3c2021-02-09 18:18:28 -08006887 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006888 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006889 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006890 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006891 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006892 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006893
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006894 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6895 // copied from the default request above. (This is necessary to ensure, for example, that
6896 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6897 // changes don't alter request matching.
6898 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6899 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006900 throw new IllegalStateException(
6901 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006902 + networkCapabilities + " vs. " + defaultNc);
6903 }
6904
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006905 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006906 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006907 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006908 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006909 }
6910 return networkRequest;
6911 }
6912
James Mattis3ce3d3c2021-02-09 18:18:28 -08006913 /**
6914 * Return the nri to be used when registering a network request. Specifically, this is used with
6915 * requests registered to track the default request. If there is currently a per-app default
6916 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6917 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006918 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6919 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006920 * @param nr the network request for the nri.
6921 * @param msgr the messenger for the nri.
6922 * @param binder the binder for the nri.
6923 * @param callingAttributionTag the calling attribution tag for the nri.
6924 * @return the nri to register.
6925 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006926 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006927 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006928 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006929 @Nullable String callingAttributionTag) {
6930 final List<NetworkRequest> requests;
6931 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6932 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006933 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006934 } else {
6935 requests = Collections.singletonList(nr);
6936 }
Roshan Pius951c0032020-12-22 15:10:42 -08006937 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006938 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006939 }
6940
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006941 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006942 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006943 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006944 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6945 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6946 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6947 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006948 }
junyulai96bd9fe2022-03-08 17:36:42 +08006949 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006950 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006951 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006952 }
6953 }
6954
fenglu3f357402015-03-20 11:29:56 -07006955 @Override
fenglub00f4882015-04-21 17:12:05 -07006956 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006957 enforceAccessPermission();
6958 NetworkAgentInfo nai = null;
6959 if (network == null) {
6960 return false;
6961 }
6962 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006963 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006964 }
6965 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006966 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006967 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006968 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006969 Integer uidReqs = mBandwidthRequests.get(uid);
6970 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006971 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006972 }
6973 mBandwidthRequests.put(uid, ++uidReqs);
6974 }
fenglu3f357402015-03-20 11:29:56 -07006975 return true;
6976 }
6977 return false;
6978 }
6979
Felipe Leme0a5ae422016-06-20 16:36:29 -07006980 private boolean isSystem(int uid) {
6981 return uid < Process.FIRST_APPLICATION_UID;
6982 }
fenglu3f357402015-03-20 11:29:56 -07006983
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006984 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006985 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006986 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006987 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006988 return;
6989 }
Hugo Benichi39621362017-02-11 17:04:43 +09006990 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6991 // Policy already enforced.
6992 return;
6993 }
paulhuaf50d7d2020-12-24 19:47:34 +08006994 final long ident = Binder.clearCallingIdentity();
6995 try {
6996 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6997 // If UID is restricted, don't allow them to bring up metered APNs.
6998 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6999 }
7000 } finally {
7001 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007002 }
7003 }
7004
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007005 @Override
7006 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007007 PendingIntent operation, @NonNull String callingPackageName,
7008 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007009 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007010 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007011 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007012 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007013 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007014 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007015 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007016 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007017 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007018 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7019 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007020
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007021 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007022 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007023 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7024 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007025 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007026 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7027 nri));
7028 return networkRequest;
7029 }
7030
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007031 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7032 mHandler.sendMessageDelayed(
7033 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007034 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007035 }
7036
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007037 @Override
7038 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007039 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007040 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007041 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007042 }
7043
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007044 // In order to implement the compatibility measure for pre-M apps that call
7045 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7046 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7047 // This ensures it has permission to do so.
7048 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7049 if (nc == null) {
7050 return false;
7051 }
7052 int[] transportTypes = nc.getTransportTypes();
7053 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7054 return false;
7055 }
7056 try {
7057 mContext.enforceCallingOrSelfPermission(
7058 android.Manifest.permission.ACCESS_WIFI_STATE,
7059 "ConnectivityService");
7060 } catch (SecurityException e) {
7061 return false;
7062 }
7063 return true;
7064 }
7065
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007066 @Override
7067 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007068 Messenger messenger, IBinder binder,
7069 @NetworkCallback.Flag int callbackFlags,
7070 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007071 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007072 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7073 enforceAccessPermission();
7074 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007075
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007076 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007077 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007078 Binder.getCallingPid(), callingUid, callingPackageName);
7079 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007080 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7081 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7082 // onLost and onAvailable callbacks when networks move in and out of the background.
7083 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7084 // can't request networks.
7085 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007086 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007087
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007088 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007089 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007090 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007091 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007092 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007093 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007094
7095 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7096 return networkRequest;
7097 }
7098
7099 @Override
7100 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007101 PendingIntent operation, @NonNull String callingPackageName,
7102 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007103 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007104 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007105 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7106 enforceAccessPermission();
7107 }
Chalard Jeandd421992021-12-16 23:16:02 +09007108 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007109 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007110 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007111 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007112 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007113
7114 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007115 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007116 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7117 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007118 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007119
WeiZhang1cc3f172021-06-03 19:02:04 -05007120 mHandler.sendMessage(mHandler.obtainMessage(
7121 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007122 }
7123
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007124 /** Returns the next Network provider ID. */
7125 public final int nextNetworkProviderId() {
7126 return mNextNetworkProviderId.getAndIncrement();
7127 }
7128
Erik Kline0c04b742016-07-07 16:50:58 +09007129 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007130 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007131 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007132 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007133 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007134 }
7135
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007136 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7137 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007138 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7139 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7140 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007141 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007142 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007143 return;
7144 }
7145
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007146 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7147 mNetworkProviderInfos.put(npi.messenger, npi);
7148 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007149 }
7150
7151 @Override
7152 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007153 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007154 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007155 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007156 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007157 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7158 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007159 }
7160
7161 @Override
7162 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007163 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007164 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007165 }
7166
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007167 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007168 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007169 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7170 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007171 Objects.requireNonNull(score);
7172 Objects.requireNonNull(caps);
7173 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007174 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007175 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007176 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7177 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007178 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7179 }
7180
Chalard Jeanbb902a52021-08-18 01:35:19 +09007181 private void updateOfferScore(final NetworkOffer offer) {
7182 final boolean yieldToBadWiFi =
7183 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7184 final NetworkOffer newOffer = new NetworkOffer(
7185 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7186 offer.caps, offer.callback, offer.providerId);
7187 if (offer.equals(newOffer)) return;
7188 handleRegisterNetworkOffer(newOffer);
7189 }
7190
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007191 @Override
7192 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007193 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007194 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7195 }
7196
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007197 private void handleUnregisterNetworkProvider(Messenger messenger) {
7198 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7199 if (npi == null) {
7200 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007201 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007202 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007203 // Unregister all the offers from this provider
7204 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7205 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007206 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007207 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7208 toRemove.add(noi);
7209 }
7210 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007211 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007212 handleUnregisterNetworkOffer(noi);
7213 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007214 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007215 }
7216
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007217 @Override
James Mattisf7027322020-12-13 16:28:14 -08007218 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007219 if (request.hasTransport(TRANSPORT_TEST)) {
7220 enforceNetworkFactoryOrTestNetworksPermission();
7221 } else {
7222 enforceNetworkFactoryPermission();
7223 }
James Mattisf7027322020-12-13 16:28:14 -08007224 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7225 if (nri != null) {
7226 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7227 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7228 mHandler.post(() -> handleReleaseNetworkRequest(
7229 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7230 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007231 }
7232
Paul Jensen1f567382015-02-13 14:18:39 -05007233 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7234 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007235 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007236 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007237 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007238 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007239 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007240
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007241 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007242 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007243 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007244
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007245 // UID ranges for users that are currently blocked by VPNs.
7246 // This array is accessed and iterated on multiple threads without holding locks, so its
7247 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7248 // (on the handler thread).
7249 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7250
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007251 // Must only be accessed on the handler thread
7252 @NonNull
7253 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7254
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007255 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007256 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007257
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007258 // Current OEM network preferences. This object must only be written to on the handler thread.
7259 // Since it is immutable and always non-null, other threads may read it if they only care
7260 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007261 @NonNull
7262 private OemNetworkPreferences mOemNetworkPreferences =
7263 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007264 // Current per-profile network preferences. This object follows the same threading rules as
7265 // the OEM network preferences above.
7266 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007267 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7268 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007269
lucaslin3ba7cc22022-12-19 02:35:33 +00007270 // Current VPN network preferences. This object follows the same threading rules as the OEM
7271 // network preferences above.
7272 @NonNull
7273 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7274 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7275
paulhu51f77dc2021-06-07 02:34:20 +00007276 // A set of UIDs that should use mobile data preferentially if available. This object follows
7277 // the same threading rules as the OEM network preferences above.
7278 @NonNull
7279 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7280
James Mattiscb1e0362021-04-06 17:07:42 -07007281 // OemNetworkPreferences activity String log entries.
7282 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7283 @NonNull
7284 private final LocalLog mOemNetworkPreferencesLogs =
7285 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7286
James Mattis02220e22021-03-13 19:27:21 -08007287 /**
7288 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7289 * @param packageName the package name to check existence of a mapping for.
7290 * @return true if a mapping exists, false otherwise
7291 */
7292 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7293 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7294 }
7295
James Mattise3ef1912020-12-20 11:09:58 -08007296 // The always-on request for an Internet-capable network that apps without a specific default
7297 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007298 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007299 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007300 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007301 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007302 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007303 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007304 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007305
James Mattisd31bdfa2020-12-23 16:37:26 -08007306 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7307 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7308 }
7309
7310 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007311 * Return the default network request currently tracking the given uid.
7312 * @param uid the uid to check.
7313 * @return the NetworkRequestInfo tracking the given uid.
7314 */
7315 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007316 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007317 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007318 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007319 // Checking the first request is sufficient as only multilayer requests will have more
7320 // than one request and for multilayer, all requests will track the same uids.
7321 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007322 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007323 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007324 highestPriorityNri = nri;
7325 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007326 }
7327 }
paulhuaa0743d2021-05-26 21:56:03 +08007328 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007329 }
7330
7331 /**
7332 * Get a copy of the network requests of the default request that is currently tracking the
7333 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007334 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7335 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007336 * @param requestorUid the uid to check the default for.
7337 * @param requestorPackageName the requestor's package name.
7338 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7339 */
7340 @NonNull
7341 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007342 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007343 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007344 getDefaultRequestTrackingUid(asUid).mRequests,
7345 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007346 }
7347
7348 /**
7349 * Copy the given nri's NetworkRequest collection.
7350 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007351 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7352 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007353 * @param requestorUid the uid to set on the copied collection.
7354 * @param requestorPackageName the package name to set on the copied collection.
7355 * @return the copied NetworkRequest collection.
7356 */
7357 @NonNull
7358 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007359 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7360 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007361 final List<NetworkRequest> requests = new ArrayList<>();
7362 for (final NetworkRequest nr : requestsToCopy) {
7363 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007364 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007365 nr.legacyType, nextNetworkRequestId(), nr.type));
7366 }
7367 return requests;
7368 }
7369
7370 @NonNull
7371 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007372 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7373 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007374 // These capabilities are for a TRACK_DEFAULT callback, so:
7375 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7376 // mDefaultRequest and a per-UID default request.
7377 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007378 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007379 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007380 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7381 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007382 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007383 restrictRequestUidsForCallerAndSetRequestorInfo(
7384 netCap, requestorUid, requestorPackageName);
7385 return netCap;
7386 }
7387
7388 /**
7389 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7390 * @param nr the network request to check for equality against.
7391 * @return the nri if one exists, null otherwise.
7392 */
7393 @Nullable
7394 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7395 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7396 if (nri.getNetworkRequestForCallback().equals(nr)) {
7397 return nri;
7398 }
7399 }
7400 return null;
7401 }
7402
7403 /**
7404 * Check if an nri is currently being managed by per-app default networking.
7405 * @param nri the nri to check.
7406 * @return true if this nri is currently being managed by per-app default networking.
7407 */
7408 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7409 // nri.mRequests.get(0) is only different from the original request filed in
7410 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7411 // functionality therefore if these two don't match, it means this particular nri is
7412 // currently being managed by a per-app default.
7413 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7414 }
7415
7416 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007417 * Determine if an nri is a managed default request that disallows default networking.
7418 * @param nri the request to evaluate
7419 * @return true if device-default networking is disallowed
7420 */
7421 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7422 // Check if this nri is a managed default that supports the default network at its
7423 // lowest priority request.
7424 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7425 final NetworkCapabilities lowestPriorityNetCap =
7426 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7427 return isPerAppDefaultRequest(nri)
7428 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7429 lowestPriorityNetCap));
7430 }
7431
Erik Kline05f2b402015-04-30 12:58:40 +09007432 // Request used to optionally keep mobile data active even when higher
7433 // priority networks like Wi-Fi are active.
7434 private final NetworkRequest mDefaultMobileDataRequest;
7435
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007436 // Request used to optionally keep wifi data active even when higher
7437 // priority networks like ethernet are active.
7438 private final NetworkRequest mDefaultWifiRequest;
7439
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007440 // Request used to optionally keep vehicle internal network always active
7441 private final NetworkRequest mDefaultVehicleRequest;
7442
James Mattisd31bdfa2020-12-23 16:37:26 -08007443 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7444 // network with no service. This NAI should never be matched against, nor should any public API
7445 // ever return the associated network. For this reason, this NAI is not in the list of available
7446 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7447 // default requests that don't support using the device default network which will ultimately
7448 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7449 @VisibleForTesting
7450 final NetworkAgentInfo mNoServiceNetwork;
7451
Chalard Jean5b409c72021-02-04 13:12:59 +09007452 // The NetworkAgentInfo currently satisfying the default request, if any.
7453 private NetworkAgentInfo getDefaultNetwork() {
7454 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007455 }
7456
James Mattis2516da32021-01-31 17:06:19 -08007457 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007458 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007459 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7460 // Currently, all network requests will have the same uids therefore checking the first
7461 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007462 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007463 if (null == uids) {
7464 continue;
7465 }
7466 for (final UidRange range : uids) {
7467 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007468 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007469 highestPriorityNri = nri;
7470 }
James Mattis2516da32021-01-31 17:06:19 -08007471 }
7472 }
7473 }
paulhuaa0743d2021-05-26 21:56:03 +08007474 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007475 }
7476
Varun Ananddf569952019-02-06 10:13:38 -08007477 @Nullable
7478 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7479 return nai != null ? nai.network : null;
7480 }
7481
7482 private void ensureRunningOnConnectivityServiceThread() {
7483 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7484 throw new IllegalStateException(
7485 "Not running on ConnectivityService thread: "
7486 + Thread.currentThread().getName());
7487 }
7488 }
7489
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007490 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007491 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7492 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007493 }
7494
Chalard Jean29d06db2018-05-02 21:14:54 +09007495 /**
7496 * Register a new agent with ConnectivityService to handle a network.
7497 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007498 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007499 * @param networkInfo the initial info associated with this network. It can be updated later :
7500 * see {@link #updateNetworkInfo}.
7501 * @param linkProperties the initial link properties of this network. They can be updated
7502 * later : see {@link #updateLinkProperties}.
7503 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007504 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007505 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007506 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007507 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007508 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007509 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007510 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007511 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007512 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7513 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007514 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7515 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7516 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007517 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007518 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007519 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007520 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007521 } else {
7522 enforceNetworkFactoryPermission();
7523 }
7524
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007525 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007526 final long token = Binder.clearCallingIdentity();
7527 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007528 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007529 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007530 } finally {
7531 Binder.restoreCallingIdentity(token);
7532 }
7533 }
7534
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007535 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007536 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007537 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7538 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007539
Chalard Jeandbc46952022-02-02 00:14:18 +09007540 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7541 // and mutate them at any time.
7542 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7543 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7544 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7545
Chalard Jean366c5252022-01-25 18:27:53 +09007546 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007547 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007548 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7549 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007550 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007551 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007552 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007553 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7554 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007555
Chalard Jeandbc46952022-02-02 00:14:18 +09007556 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007557 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007558 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007559 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007560 mDeps.getNetworkStack().makeNetworkMonitor(
7561 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007562 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7563 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007564 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007565 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007566 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007567 }
7568
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007569 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007570 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007571 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007572 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007573 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007574 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7575 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7576 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007577
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007578 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007579
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007580 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007581 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007582 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007583 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007584
7585 try {
7586 networkMonitor.start();
7587 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007588 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007589 }
Chalard Jean366c5252022-01-25 18:27:53 +09007590
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007591 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007592 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007593 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007594 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007595 }
7596
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007597 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7598 @NonNull public final NetworkOffer offer;
7599
7600 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7601 this.offer = offer;
7602 }
7603
7604 @Override
7605 public void binderDied() {
7606 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7607 }
7608 }
7609
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007610 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7611 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7612 if (npi.providerId == providerId) return true;
7613 }
7614 return false;
7615 }
7616
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007617 /**
7618 * Register or update a network offer.
7619 * @param newOffer The new offer. If the callback member is the same as an existing
7620 * offer, it is an update of that offer.
7621 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007622 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007623 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7624 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007625 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007626 // This may actually happen if a provider updates its score or registers and then
7627 // immediately unregisters. The offer would still be in the handler queue, but the
7628 // provider would have been removed.
7629 if (DBG) log("Received offer from an unregistered provider");
7630 return;
7631 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007632 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7633 if (null != existingOffer) {
7634 handleUnregisterNetworkOffer(existingOffer);
7635 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007636 if (DBG) {
7637 // handleUnregisterNetworkOffer has already logged the old offer
7638 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7639 }
7640 } else {
7641 if (DBG) {
7642 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7643 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007644 }
7645 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7646 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007647 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007648 } catch (RemoteException e) {
7649 noi.binderDied();
7650 return;
7651 }
7652 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007653 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007654 }
7655
7656 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7657 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007658 if (DBG) {
7659 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7660 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007661
7662 // If the provider removes the offer and dies immediately afterwards this
7663 // function may be called twice in a row, but the array will no longer contain
7664 // the offer.
7665 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007666 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007667 }
7668
7669 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7670 @NonNull final INetworkOfferCallback callback) {
7671 ensureRunningOnConnectivityServiceThread();
7672 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007673 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007674 }
7675 return null;
7676 }
7677
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007678 /**
7679 * Called when receiving LinkProperties directly from a NetworkAgent.
7680 * Stores into |nai| any data coming from the agent that might also be written to the network's
7681 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7682 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007683 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007684 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007685 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7686 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007687 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007688 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007689 }
7690
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007691 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007692 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007693 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007694
Lorenzo Colittid523d142020-04-01 20:16:30 +09007695 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7696 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7697 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007698 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007699
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007700 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007701
7702 // update filtering rules, need to happen after the interface update so netd knows about the
7703 // new interface (the interface name -> index map becomes initialized)
7704 updateVpnFiltering(newLp, oldLp, networkAgent);
7705
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007706 updateMtu(newLp, oldLp);
7707 // TODO - figure out what to do for clat
7708// for (LinkProperties lp : newLp.getStackedLinks()) {
7709// updateMtu(lp, null);
7710// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007711 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007712 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7713 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007714
Erik Klineb9888902016-04-05 13:30:49 +09007715 updateRoutes(newLp, oldLp, netId);
7716 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007717 // Make sure LinkProperties represents the latest private DNS status.
7718 // This does not need to be done before updateDnses because the
7719 // LinkProperties are not the source of the private DNS configuration.
7720 // updateDnses will fetch the private DNS configuration from DnsManager.
7721 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007722
Chalard Jean5b409c72021-02-04 13:12:59 +09007723 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007724 handleApplyDefaultProxy(newLp.getHttpProxy());
7725 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007726 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007727 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007728
7729 updateWakeOnLan(newLp);
7730
Hai Shalome58bdc62021-01-11 18:45:34 -08007731 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7732 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7733 // does, it needs to be merged here.
7734 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7735 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007736
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007737 // TODO - move this check to cover the whole function
7738 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007739 synchronized (networkAgent) {
7740 networkAgent.linkProperties = newLp;
7741 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007742 // Start or stop DNS64 detection and 464xlat according to network state.
7743 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007744 // Notify NSS when relevant events happened. Currently, NSS only cares about
7745 // interface changed to update clat interfaces accounting.
7746 final boolean interfacesChanged = oldLp == null
7747 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7748 if (interfacesChanged) {
7749 notifyIfacesChangedForNetworkStats();
7750 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007751 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7752 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007753 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007754 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007755
7756 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007757 }
7758
Hai Shalome58bdc62021-01-11 18:45:34 -08007759 /**
7760 * @param naData captive portal data from NetworkAgent
7761 * @param apiData captive portal data from capport API
7762 */
7763 @Nullable
7764 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7765 CaptivePortalData apiData) {
7766 if (naData == null || apiData == null) {
7767 return naData == null ? apiData : naData;
7768 }
7769 final CaptivePortalData.Builder captivePortalBuilder =
7770 new CaptivePortalData.Builder(naData);
7771
7772 if (apiData.isCaptive()) {
7773 captivePortalBuilder.setCaptive(true);
7774 }
7775 if (apiData.isSessionExtendable()) {
7776 captivePortalBuilder.setSessionExtendable(true);
7777 }
7778 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7779 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7780 // otherwise data would be inconsistent. Prefer the capport API info if present,
7781 // as it can generally be refreshed more often.
7782 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7783 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7784 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7785 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7786 // No source has time / bytes remaining information: surface the newest refresh time
7787 // for other fields
7788 captivePortalBuilder.setRefreshTime(
7789 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7790 }
7791
Hai Shalom7c6ab402021-02-04 19:34:06 -08007792 // Prioritize the user portal URL from the network agent if the source is authenticated.
7793 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7794 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7795 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7796 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007797 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007798 // Prioritize the venue information URL from the network agent if the source is
7799 // authenticated.
7800 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7801 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7802 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7803 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007804 }
7805 return captivePortalBuilder.build();
7806 }
7807
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007808 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007809 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007810 // marks on unsupported interfaces is harmless.
7811 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7812 return;
7813 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007814
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007815 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7816 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7817
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007818 // Mask/mark of zero will not detect anything interesting.
7819 // Don't install rules unless both values are nonzero.
7820 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007821 return;
7822 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007823
7824 final String prefix = "iface:" + iface;
7825 try {
7826 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007827 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007828 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007829 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007830 }
7831 } catch (Exception e) {
7832 loge("Exception modifying wakeup packet monitoring: " + e);
7833 }
7834
Joel Scherpelza235a812017-05-22 13:47:41 +09007835 }
7836
Junyu Lai970963e2022-10-25 15:46:47 +08007837 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09007838 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007839 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007840 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08007841 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09007842 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007843 for (final String iface : interfaceDiff.added) {
7844 try {
7845 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007846 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007847 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007848 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7849 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007850 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007851 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007852 }
Paul Jensenbff73492014-04-28 10:33:11 -04007853 }
7854 }
Chalard Jean9589e722019-11-19 19:03:53 +09007855 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007856 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007857 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007858 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007859 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007860 } catch (Exception e) {
7861 loge("Exception removing interface: " + e);
7862 }
7863 }
7864 }
7865
Tyler Weare4314862019-12-05 14:55:30 -08007866 // TODO: move to frameworks/libs/net.
7867 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7868 final String nextHop;
7869
7870 switch (route.getType()) {
7871 case RouteInfo.RTN_UNICAST:
7872 if (route.hasGateway()) {
7873 nextHop = route.getGateway().getHostAddress();
7874 } else {
7875 nextHop = INetd.NEXTHOP_NONE;
7876 }
7877 break;
7878 case RouteInfo.RTN_UNREACHABLE:
7879 nextHop = INetd.NEXTHOP_UNREACHABLE;
7880 break;
7881 case RouteInfo.RTN_THROW:
7882 nextHop = INetd.NEXTHOP_THROW;
7883 break;
7884 default:
7885 nextHop = INetd.NEXTHOP_NONE;
7886 break;
7887 }
7888
7889 final RouteInfoParcel rip = new RouteInfoParcel();
7890 rip.ifName = route.getInterface();
7891 rip.destination = route.getDestination().toString();
7892 rip.nextHop = nextHop;
7893 rip.mtu = route.getMtu();
7894
7895 return rip;
7896 }
7897
Paul Jensene0fd4a82014-08-06 15:51:33 -04007898 /**
7899 * Have netd update routes from oldLp to newLp.
7900 * @return true if routes changed between oldLp and newLp
7901 */
Junyu Lai970963e2022-10-25 15:46:47 +08007902 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7903 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007904 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007905 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7906 new CompareOrUpdateResult<>(
7907 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08007908 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08007909 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007910
7911 // add routes before removing old in case it helps with continuous connectivity
7912
Chalard Jean9dd11612018-06-04 16:52:49 +09007913 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007914 for (RouteInfo route : routeDiff.added) {
7915 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007916 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007917 try {
Tyler Weare4314862019-12-05 14:55:30 -08007918 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007919 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007920 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007921 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007922 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007923 }
7924 }
7925 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007926 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007927 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007928 try {
Tyler Weare4314862019-12-05 14:55:30 -08007929 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007930 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007931 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007932 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007933 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007934 }
7935 }
7936
7937 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007938 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007939 try {
Tyler Weare4314862019-12-05 14:55:30 -08007940 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007941 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007942 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007943 }
7944 }
Tyler Weare4314862019-12-05 14:55:30 -08007945
7946 for (RouteInfo route : routeDiff.updated) {
7947 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7948 try {
7949 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7950 } catch (Exception e) {
7951 loge("Exception in networkUpdateRouteParcel: " + e);
7952 }
7953 }
7954 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7955 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007956 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007957
Junyu Lai970963e2022-10-25 15:46:47 +08007958 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7959 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09007960 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7961 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007962 }
Erik Klineb9888902016-04-05 13:30:49 +09007963
Erik Kline31b4a9e2018-01-11 21:07:29 +09007964 if (DBG) {
7965 final Collection<InetAddress> dnses = newLp.getDnsServers();
7966 log("Setting DNS servers for network " + netId + " to " + dnses);
7967 }
Erik Klineb9888902016-04-05 13:30:49 +09007968 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007969 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007970 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007971 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007972 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007973 }
Erik Kline54e35c02017-04-07 15:29:29 +09007974 }
7975
Junyu Lai970963e2022-10-25 15:46:47 +08007976 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7977 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007978 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7979 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007980 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7981 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007982
7983 if (!wasFiltering && !needsFiltering) {
7984 // Nothing to do.
7985 return;
7986 }
7987
7988 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7989 // Nothing changed.
7990 return;
7991 }
7992
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007993 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007994 if (ranges == null || ranges.isEmpty()) {
7995 return;
7996 }
7997
Qingxi Libb8da982020-01-17 17:54:27 -08007998 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007999 // TODO: this create a window of opportunity for apps to receive traffic between the time
8000 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008001 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008002 // old rules are being removed.
8003 if (wasFiltering) {
8004 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8005 }
8006 if (needsFiltering) {
8007 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8008 }
8009 }
8010
Valentin Iftime9fa35092019-09-24 13:32:13 +02008011 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008012 if (mWolSupportedInterfaces == null) {
8013 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008014 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008015 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008016 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8017 }
8018
Luke Huangb913c812018-08-24 20:33:16 +08008019 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008020 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008021 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008022 }
8023 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008024 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008025 }
Luke Huangb913c812018-08-24 20:33:16 +08008026 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008027 }
8028
Chalard Jean62edfd82019-12-02 18:39:29 +09008029 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8030 @NonNull final NetworkCapabilities newNc) {
8031 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8032 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008033 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008034 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008035 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008036 } catch (RemoteException | ServiceSpecificException e) {
8037 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008038 }
8039 }
8040 }
8041
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008042 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008043 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008044 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008045 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008046 underlyingNetworks = underlyingNetworksOrDefault(
8047 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008048 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008049 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8050 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008051 // metered if any underlying is metered, or originally declared metered by the agent.
8052 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008053 boolean roaming = false; // roaming if any underlying is roaming
8054 boolean congested = false; // congested if any underlying is congested
8055 boolean suspended = true; // suspended if all underlying are suspended
8056
8057 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008058 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008059 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008060 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008061 for (Network underlyingNetwork : underlyingNetworks) {
8062 final NetworkAgentInfo underlying =
8063 getNetworkAgentInfoForNetwork(underlyingNetwork);
8064 if (underlying == null) continue;
8065
8066 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8067 hadUnderlyingNetworks = true;
8068 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008069 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008070 }
8071
8072 // Merge capabilities of this underlying network. For bandwidth, assume the
8073 // worst case.
8074 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8075 underlyingCaps.getLinkDownstreamBandwidthKbps());
8076 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8077 underlyingCaps.getLinkUpstreamBandwidthKbps());
8078 // If this underlying network is metered, the VPN is metered (it may cost money
8079 // to send packets on this network).
8080 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8081 // If this underlying network is roaming, the VPN is roaming (the billing structure
8082 // is different than the usual, local one).
8083 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8084 // If this underlying network is congested, the VPN is congested (the current
8085 // condition of the network affects the performance of this network).
8086 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8087 // If this network is not suspended, the VPN is not suspended (the VPN
8088 // is able to transfer some data).
8089 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008090 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008091 }
8092 }
8093 if (!hadUnderlyingNetworks) {
8094 // No idea what the underlying networks are; assume reasonable defaults
8095 metered = true;
8096 roaming = false;
8097 congested = false;
8098 suspended = false;
8099 }
8100
Chalard Jean1d420b32022-10-12 16:39:37 +09008101 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008102 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8103 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8104 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8105 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8106 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8107 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008108 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008109 }
8110
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008111 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008112 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8113 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8114 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008115 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008116 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008117 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008118 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008119 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8120 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008121 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008122 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008123 if (nai.everConnected()
8124 && !nai.isVPN()
8125 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008126 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008127 // does not cause any request (that is not a listen) currently matching that agent to
8128 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008129 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008130 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008131 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008132 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008133 }
8134
Paul Jensen53f08952015-06-16 14:27:36 -04008135 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008136 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008137 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008138 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008139 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008140 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008141 }
Chalard Jean254bd162022-08-25 13:04:51 +09008142 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008143 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008144 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008145 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008146 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008147 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008148 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008149 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008150 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008151 }
Chalard Jean254bd162022-08-25 13:04:51 +09008152 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008153 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8154 } else {
8155 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8156 }
lucasline117e2e2019-10-22 18:27:33 +08008157 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008158
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008159 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008160 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8161 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008162 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008163 }
8164
Lorenzo Colittibd079452021-07-02 11:47:57 +09008165 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008166 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008167 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008168 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008169 }
8170
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008171 return newNc;
8172 }
8173
Lorenzo Colitti44840702021-01-11 22:27:57 +09008174 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8175 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8176 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8177 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8178 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8179 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8180 if (prevSuspended != suspended) {
8181 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8182 // onResumed have been removed.
8183 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8184 : ConnectivityManager.CALLBACK_RESUMED);
8185 }
8186 if (prevSuspended != suspended || prevRoaming != roaming) {
8187 // updateNetworkInfo will mix in the suspended info from the capabilities and
8188 // take appropriate action for the network having possibly changed state.
8189 updateNetworkInfo(nai, nai.networkInfo);
8190 }
8191 }
8192
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008193 /**
8194 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8195 *
8196 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8197 * capabilities we manage and store in {@code nai}, such as validated status and captive
8198 * portal status)
8199 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8200 * potentially triggers rematches.
8201 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8202 * change.)
8203 *
8204 * @param oldScore score of the network before any of the changes that prompted us
8205 * to call this function.
8206 * @param nai the network having its capabilities updated.
8207 * @param nc the new network capabilities.
8208 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008209 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008210 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008211 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008212 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008213 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8214 if (null != differences) {
8215 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8216 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008217 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008218 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008219
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008220 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008221 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008222 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008223
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008224 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008225 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8226 // the change we're processing can't affect any requests, it can only affect the listens
8227 // on this network. We might have been called by rematchNetworkAndRequests when a
8228 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008229 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008230 } else {
8231 // If the requestable capabilities have changed or the score changed, we can't have been
8232 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008233 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008234 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008235 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008236 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008237
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008238 final boolean oldMetered = prevNc.isMetered();
8239 final boolean newMetered = newNc.isMetered();
8240 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008241
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008242 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008243 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8244 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008245 }
junyulaif2c67e42018-08-07 19:50:45 +08008246
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008247 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8248 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008249
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008250 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008251 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008252 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008253 }
8254
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008255 // This network might have been underlying another network. Propagate its capabilities.
8256 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008257
8258 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008259 mDnsManager.updateTransportsForNetwork(
8260 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008261 }
lucaslin53e8a262021-06-08 01:43:59 +08008262
8263 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008264 }
8265
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008266 /** Convenience method to update the capabilities for a given network. */
8267 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008268 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008269 }
8270
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008271 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008272 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008273 *
8274 * Ingress interface filtering enforces that all apps under the given network can only receive
8275 * packets from the network's interface (and loopback). This is important for VPNs because
8276 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8277 * non-VPN interfaces.
8278 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008279 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008280 * 1. the network is an app VPN (not legacy VPN)
8281 * 2. the VPN does not allow bypass
8282 * 3. the VPN is fully-routed
8283 * 4. the VPN interface is non-null
8284 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008285 * @see INetd#firewallAddUidInterfaceRules
8286 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008287 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008288 @Nullable
8289 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008290 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008291 if (nc == null || lp == null) return null;
8292 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008293 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008294 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008295 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008296 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008297 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008298 && !lp.hasExcludeRoute()) {
8299 return lp.getInterfaceName();
8300 }
8301 return null;
8302 }
8303
8304 /**
8305 * Returns whether we need to set interface filtering rule or not
8306 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008307 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008308 String isolationIface) {
8309 // Allow rules are always needed if VPN isolation is enabled.
8310 if (isolationIface != null) return true;
8311
8312 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8313 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8314 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8315 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008316 }
8317
Chiachang Wang28afaff2020-12-10 22:24:47 +08008318 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8319 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8320 int index = 0;
8321 for (UidRange range : ranges) {
8322 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8323 index++;
8324 }
8325 return stableRanges;
8326 }
8327
Chalard Jeane6c95272022-01-25 21:04:21 +09008328 private static UidRangeParcel[] intsToUidRangeStableParcels(
8329 final @NonNull ArraySet<Integer> uids) {
8330 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8331 int index = 0;
8332 for (int uid : uids) {
8333 stableRanges[index] = new UidRangeParcel(uid, uid);
8334 index++;
8335 }
8336 return stableRanges;
8337 }
8338
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008339 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8340 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8341 for (int i = 0; i < ranges.length; i++) {
8342 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8343 }
8344 return stableRanges;
8345 }
8346
Ken Chen5e65a852020-12-24 12:59:10 +08008347 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8348 int[] exemptUids) {
8349 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8350 try {
8351 mNetd.socketDestroy(ranges, exemptUids);
8352 } catch (Exception e) {
8353 loge("Exception in socket destroy: ", e);
8354 }
8355 }
8356 }
8357
paulhuaa0743d2021-05-26 21:56:03 +08008358 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008359 int[] exemptUids = new int[2];
8360 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8361 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8362 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8363 exemptUids[0] = VPN_UID;
8364 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8365 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8366
8367 maybeCloseSockets(nai, ranges, exemptUids);
8368 try {
8369 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008370 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008371 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008372 } else {
paulhu0e79d952021-06-09 16:11:35 +08008373 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008374 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008375 }
8376 } catch (Exception e) {
8377 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8378 " on netId " + nai.network.netId + ". " + e);
8379 }
8380 maybeCloseSockets(nai, ranges, exemptUids);
8381 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008382
lucaslin53e8a262021-06-08 01:43:59 +08008383 private boolean isProxySetOnAnyDefaultNetwork() {
8384 ensureRunningOnConnectivityServiceThread();
8385 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8386 final NetworkAgentInfo nai = nri.getSatisfier();
8387 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8388 return true;
8389 }
8390 }
8391 return false;
8392 }
8393
8394 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8395 NetworkCapabilities newNc) {
8396 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8397 // the proxy might be changed since the default network satisfied by the apps might also
8398 // changed.
8399 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8400 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008401 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8402 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008403 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008404 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8405 mProxyTracker.sendProxyBroadcast();
8406 }
8407 }
8408
Chalard Jeane6c95272022-01-25 21:04:21 +09008409 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8410 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008411 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8412 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008413 if (null == prevRanges) prevRanges = new ArraySet<>();
8414 if (null == newRanges) newRanges = new ArraySet<>();
8415 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8416
8417 prevRanges.removeAll(newRanges);
8418 newRanges.removeAll(prevRangesCopy);
8419
8420 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008421 // When updating the VPN uid routing rules, add the new range first then remove the old
8422 // range. If old range were removed first, there would be a window between the old
8423 // range being removed and the new range being added, during which UIDs contained
8424 // in both ranges are not subject to any VPN routing rules. Adding new range before
8425 // removing old range works because, unlike the filtering rules below, it's possible to
8426 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008427 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8428 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8429 // [1-5] & [1-2],[4-5] == [3]
8430 // Then we can do:
8431 // maybeCloseSockets([3])
8432 // mNetd.networkAddUidRanges([1-2],[4-5])
8433 // mNetd.networkRemoveUidRanges([1-5])
8434 // maybeCloseSockets([3])
8435 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8436 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008437 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008438 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008439 }
8440 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008441 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008442 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008443 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8444 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008445 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8446 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008447 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008448 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008449 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8450 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8451 // were added first and then newRanges got removed later, there would be only one uid
8452 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8453 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8454 // Note that this is in contrast with the (more robust) update of VPN routing rules
8455 // above, where the addition of new ranges happens before the removal of old ranges.
8456 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8457 // to be removed will never overlap with the new range to be added.
8458 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008459 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8460 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008461 }
8462 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008463 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008464 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008465 } catch (Exception e) {
8466 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008467 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008468 }
8469 }
8470
Chalard Jeande665262022-02-25 16:12:12 +09008471 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008472 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8473 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008474 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8475 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008476 if (prevEmpty && newEmpty) return;
8477
8478 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008479 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008480 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008481 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008482
8483 if (prevUids.equals(newUids)) return;
8484
8485 // This implementation is very simple and vastly faster for sets of Integers than
8486 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8487 // a key computed from the value and has storage for that.
8488 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8489 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8490 toRemove.removeAll(newUids);
8491 toAdd.removeAll(prevUids);
8492
8493 try {
8494 if (!toAdd.isEmpty()) {
8495 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8496 nai.network.netId,
8497 intsToUidRangeStableParcels(toAdd),
8498 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8499 }
8500 if (!toRemove.isEmpty()) {
8501 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8502 nai.network.netId,
8503 intsToUidRangeStableParcels(toRemove),
8504 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8505 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008506 } catch (ServiceSpecificException e) {
8507 // Has the interface disappeared since the network was built ?
8508 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008509 } catch (RemoteException e) {
8510 // Netd died. This usually causes a runtime restart anyway.
8511 }
8512 }
8513
Junyu Lai2ed7d412022-10-07 16:52:21 +08008514 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8515 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008516 ensureRunningOnConnectivityServiceThread();
8517
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008518 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008519 // Ignore updates for disconnected networks
8520 return;
8521 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008522 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008523 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008524 + "; created=" + nai.getCreatedTime()
8525 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008526 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008527 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8528 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008529 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008530 }
8531
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008532 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8533 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008534 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008535 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008536 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008537 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8538 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8539 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008540 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8541 // need to be sent as a separate extra.
8542 final NetworkRequest req = nri.isMultilayerRequest()
8543 ? nri.getActiveRequest()
8544 // Non-multilayer listen requests do not have an active request
8545 : nri.mRequests.get(0);
8546 if (req == null) {
8547 Log.wtf(TAG, "No request in NRI " + nri);
8548 }
8549 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008550 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008551 sendIntent(nri.mPendingIntent, intent);
8552 }
8553 // else not handled
8554 }
8555
Michael Groover73f69482023-01-27 11:01:25 -06008556 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
8557 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008558 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8559 mPendingIntentWakeLock.acquire();
8560 try {
8561 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008562 final BroadcastOptions options = BroadcastOptions.makeBasic();
8563 if (SdkLevel.isAtLeastT()) {
8564 // Explicitly disallow the receiver from starting activities, to prevent apps from
8565 // utilizing the PendingIntent as a backdoor to do this.
8566 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8567 }
8568 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8569 null /* requiredPermission */,
8570 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008571 } catch (PendingIntent.CanceledException e) {
8572 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8573 mPendingIntentWakeLock.release();
8574 releasePendingNetworkRequest(pendingIntent);
8575 }
8576 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8577 }
8578
8579 @Override
8580 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8581 String resultData, Bundle resultExtras) {
8582 if (DBG) log("Finished sending " + pendingIntent);
8583 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008584 // Release with a delay so the receiving client has an opportunity to put in its
8585 // own request.
8586 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008587 }
8588
Chalard Jean46bfbf02022-02-02 00:56:25 +09008589 // networkAgent is only allowed to be null if notificationType is
8590 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8591 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008592 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008593 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008594 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008595 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008596 // Default request has no msgr. Also prevents callbacks from being invoked for
8597 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8598 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8599 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008600 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008601 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008602 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008603 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008604 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008605 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008606 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008607 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8608 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008609 }
Roshan Pius951c0032020-12-22 15:10:42 -08008610 final boolean includeLocationSensitiveInfo =
8611 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008612 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008613 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008614 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008615 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008616 networkCapabilitiesRestrictedForCallerPermissions(
8617 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8618 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008619 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008620 nri.mCallingAttributionTag);
8621 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008622 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8623 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008624 // For this notification, arg1 contains the blocked status.
8625 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008626 break;
8627 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008628 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008629 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008630 break;
8631 }
8632 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008633 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008634 final NetworkCapabilities netCap =
8635 networkCapabilitiesRestrictedForCallerPermissions(
8636 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8637 putParcelable(
8638 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008639 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008640 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008641 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008642 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008643 break;
8644 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008645 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008646 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8647 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008648 break;
8649 }
junyulaif2c67e42018-08-07 19:50:45 +08008650 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008651 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008652 msg.arg1 = arg1;
8653 break;
8654 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008655 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008656 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008657 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008658 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008659 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008660 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008661 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008662 }
James Mattis45d81842021-01-10 14:24:24 -08008663 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008664 } catch (RemoteException e) {
8665 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008666 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008667 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008668 }
8669
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008670 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8671 bundle.putParcelable(t.getClass().getSimpleName(), t);
8672 }
8673
Chalard Jean0702f982021-09-16 21:50:07 +09008674 /**
8675 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8676 *
8677 * When a request should be assigned to a new network, it is normally lingered to give
8678 * time for apps to gracefully migrate their connections. When both networks are on the same
8679 * radio, but that radio can't do time-sharing efficiently, this may end up being
8680 * counter-productive because any traffic on the old network may drastically reduce the
8681 * performance of the new network.
8682 * The stack supports a configuration to let modem vendors state that their radio can't
8683 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8684 * from one cell network to another can't be done gracefully.
8685 *
8686 * @param oldNai the old network serving the request
8687 * @param newNai the new network serving the request
8688 * @return whether the switch can be graceful
8689 */
8690 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8691 @NonNull final NetworkAgentInfo newSatisfier) {
8692 if (mCellularRadioTimesharingCapable) return true;
8693 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8694 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8695 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8696 }
8697
Paul Jensenaf94b982014-09-30 15:37:41 -04008698 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008699 if (nai.numRequestNetworkRequests() != 0) {
8700 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8701 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008702 // Ignore listening and track default requests.
8703 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008704 loge("Dead network still had at least " + nr);
8705 break;
8706 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008707 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008708 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008709 }
8710
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008711 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8712 if (oldNetwork == null) {
8713 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8714 return;
8715 }
Chalard Jean49707572019-12-10 21:07:02 +09008716 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008717
8718 // If we get here it means that the last linger timeout for this network expired. So there
8719 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008720 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008721
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008722 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008723 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008724 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008725 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008726 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008727 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008728 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008729 }
8730
James Mattise3ef1912020-12-20 11:09:58 -08008731 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8732 boolean isDefaultChanged = false;
8733 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8734 final NetworkReassignment.RequestReassignment reassignment =
8735 changes.getReassignment(defaultRequestInfo);
8736 if (null == reassignment) {
8737 continue;
8738 }
8739 // reassignment only contains those instances where the satisfying network changed.
8740 isDefaultChanged = true;
8741 // Notify system services of the new default.
8742 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8743 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008744
James Mattise3ef1912020-12-20 11:09:58 -08008745 if (isDefaultChanged) {
8746 // Hold a wakelock for a short time to help apps in migrating to a new default.
8747 scheduleReleaseNetworkTransitionWakelock();
8748 }
8749 }
8750
8751 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8752 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8753 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8754 if (DBG) {
8755 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8756 }
Chalard Jean8e382112019-12-03 20:45:30 +09008757
James Mattisd31bdfa2020-12-23 16:37:26 -08008758 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8759 if (newDefaultNetwork != null) {
8760 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008761 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008762
James Mattisd31bdfa2020-12-23 16:37:26 -08008763 // Set an app level managed default and return since further processing only applies to the
8764 // default network.
8765 if (mDefaultRequest != nri) {
8766 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8767 return;
8768 }
8769
8770 makeDefaultNetwork(newDefaultNetwork);
8771
James Mattise3ef1912020-12-20 11:09:58 -08008772 if (oldDefaultNetwork != null) {
8773 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8774 }
8775 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008776 handleApplyDefaultProxy(null != newDefaultNetwork
8777 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8778 updateTcpBufferSizes(null != newDefaultNetwork
8779 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008780 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008781 }
8782
James Mattisd31bdfa2020-12-23 16:37:26 -08008783 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8784 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8785 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8786 try {
8787 if (VDBG) {
8788 log("Setting default network for " + nri
8789 + " using UIDs " + nri.getUids()
8790 + " with old network " + (oldDefaultNetwork != null
8791 ? oldDefaultNetwork.network().getNetId() : "null")
8792 + " and new network " + (newDefaultNetwork != null
8793 ? newDefaultNetwork.network().getNetId() : "null"));
8794 }
8795 if (nri.getUids().isEmpty()) {
8796 throw new IllegalStateException("makeDefaultForApps called without specifying"
8797 + " any applications to set as the default." + nri);
8798 }
8799 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008800 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008801 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008802 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008803 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008804 }
8805 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008806 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008807 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008808 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008809 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008810 }
8811 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008812 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008813 }
8814 }
8815
Junyu Lai35665cc2022-12-19 17:37:48 +08008816 /**
8817 * Collect restricted uid ranges for the given network and UserHandle, these uids
8818 * are not restricted for matched enterprise networks but being restricted for non-matched
8819 * enterprise networks and non-enterprise networks.
8820 */
8821 @NonNull
8822 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
8823 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
8824 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
8825 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
8826 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
8827
8828 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
8829 // The NC is built from a `ProfileNetworkPreference` which has only one
8830 // enterprise ID, so it's guaranteed to have exactly one.
8831 final int prefId = pref.capabilities.getEnterpriseIds()[0];
8832 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
8833 continue;
8834 }
8835 }
8836
8837 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
8838 pref.capabilities.getUidRanges())) {
8839 throw new IllegalArgumentException(
8840 "Overlapping uid range in preference: " + pref);
8841 }
8842 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
8843 }
8844 return restrictedUidRanges;
8845 }
8846
8847 private void updateProfileAllowedNetworks() {
8848 ensureRunningOnConnectivityServiceThread();
8849 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
8850 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
8851 .getUserHandles(true /* excludeDying */);
8852 if (users.isEmpty()) {
8853 throw new IllegalStateException("No user is available");
8854 }
8855
8856 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8857 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
8858 for (final UserHandle user : users) {
8859 final ArraySet<UidRange> restrictedUidRanges =
8860 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
8861 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
8862 UidRange.createForUser(user), restrictedUidRanges));
8863 }
8864
8865 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
8866 configs.add(new NativeUidRangeConfig(
8867 nai.network.netId, rangesParcel, 0 /* subPriority */));
8868 }
8869
8870 // The netd API replaces the previous configs with the current configs.
8871 // Thus, for network disconnection or preference removal, no need to
8872 // unset previous config. Instead, collecting all currently needed
8873 // configs and issue to netd.
8874 try {
8875 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
8876 } catch (ServiceSpecificException e) {
8877 // Has the interface disappeared since the network was built?
8878 } catch (RemoteException e) {
8879 // Netd died. This usually causes a runtime restart anyway.
8880 }
8881 }
8882
James Mattisd31bdfa2020-12-23 16:37:26 -08008883 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8884 try {
8885 if (null != newDefaultNetwork) {
8886 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8887 } else {
8888 mNetd.networkClearDefault();
8889 }
8890 } catch (RemoteException | ServiceSpecificException e) {
8891 loge("Exception setting default network :" + e);
8892 }
8893 }
8894
Chalard Jean05cbe972019-12-09 11:50:38 +09008895 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008896 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008897 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008898 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008899 processNewlySatisfiedListenRequests(nai);
8900 }
8901
8902 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008903 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8904 if (nri.isMultilayerRequest()) {
8905 continue;
8906 }
8907 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008908 if (!nr.isListen()) continue;
8909 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008910 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008911 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8912 }
8913 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008914 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008915
Chalard Jeancd397a22019-11-22 22:33:33 +09008916 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008917 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8918 if (nri.isMultilayerRequest()) {
8919 continue;
8920 }
8921 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008922 if (!nr.isListen()) continue;
8923 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8924 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008925 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008926 }
8927 }
8928 }
8929
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008930 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008931 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008932 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008933 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008934 @Nullable public final NetworkRequest mOldNetworkRequest;
8935 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008936 @Nullable public final NetworkAgentInfo mOldNetwork;
8937 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008938 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008939 @Nullable final NetworkRequest oldNetworkRequest,
8940 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008941 @Nullable final NetworkAgentInfo oldNetwork,
8942 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008943 mNetworkRequestInfo = networkRequestInfo;
8944 mOldNetworkRequest = oldNetworkRequest;
8945 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008946 mOldNetwork = oldNetwork;
8947 mNewNetwork = newNetwork;
8948 }
Chalard Jean49707572019-12-10 21:07:02 +09008949
8950 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008951 final NetworkRequest requestToShow = null != mNewNetworkRequest
8952 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8953 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008954 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8955 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008956 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008957 }
8958
Chalard Jean46a62372019-12-10 21:25:24 +09008959 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008960
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008961 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008962 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008963 }
8964
8965 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008966 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008967 // The code is never supposed to add two reassignments of the same request. Make
8968 // sure this stays true, but without imposing this expensive check on all
8969 // reassignments on all user devices.
8970 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008971 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008972 throw new IllegalStateException("Trying to reassign ["
8973 + reassignment + "] but already have ["
8974 + existing + "]");
8975 }
8976 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008977 }
Chalard Jean46a62372019-12-10 21:25:24 +09008978 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008979 }
8980
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008981 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008982 // the passed request.
8983 @Nullable
8984 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008985 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008986 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008987 }
8988 return null;
8989 }
Chalard Jean49707572019-12-10 21:07:02 +09008990
8991 public String toString() {
8992 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8993 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008994 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008995 for (final RequestReassignment rr : getRequestReassignments()) {
8996 sj.add(rr.toString());
8997 }
8998 return sj.toString();
8999 }
9000
9001 public String debugString() {
9002 final StringBuilder sb = new StringBuilder();
9003 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009004 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009005 for (final RequestReassignment rr : getRequestReassignments()) {
9006 sb.append("\n ").append(rr);
9007 }
9008 return sb.append("\n").toString();
9009 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009010 }
9011
Chalard Jean24344d72019-12-04 13:32:31 +09009012 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009013 @Nullable final NetworkRequest previousRequest,
9014 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009015 @Nullable final NetworkAgentInfo previousSatisfier,
9016 @Nullable final NetworkAgentInfo newSatisfier,
9017 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009018 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009019 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009020 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009021 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009022 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009023 }
James Mattisa076c532020-12-02 14:12:41 -08009024 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009025 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009026 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009027 // If this network switch can't be supported gracefully, the request is not
9028 // lingered. This allows letting go of the network sooner to reclaim some
9029 // performance on the new network, since the radio can't do both at the same
9030 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009031 //
9032 // Also don't linger the request if the old network has been destroyed.
9033 // A destroyed network does not provide actual network connectivity, so
9034 // lingering it is not useful. In particular this ensures that a destroyed
9035 // network is outscored by its replacement,
9036 // then it is torn down immediately instead of being lingered, and any apps that
9037 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009038 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9039 }
Chalard Jean24344d72019-12-04 13:32:31 +09009040 } else {
9041 if (VDBG || DDBG) log(" accepting network in place of null");
9042 }
junyulai0ac374f2020-12-14 18:41:52 +08009043
9044 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9045 // and immediately satisfies a request then remove the timer. This will happen for
9046 // all networks except in the case of an underlying network for a VCN.
9047 if (newSatisfier.isNascent()) {
9048 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009049 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009050 }
9051
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009052 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009053 newSatisfier.unlingerRequest(newRequest.requestId);
9054 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009055 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009056 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009057 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009058 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009059 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009060 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009061 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009062 }
James Mattisa076c532020-12-02 14:12:41 -08009063 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009064 }
James Mattisa076c532020-12-02 14:12:41 -08009065 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009066 }
9067
James Mattisa076c532020-12-02 14:12:41 -08009068 /**
9069 * This function is triggered when something can affect what network should satisfy what
9070 * request, and it computes the network reassignment from the passed collection of requests to
9071 * network match to the one that the system should now have. That data is encoded in an
9072 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9073 * satisfier.
9074 *
9075 * After the reassignment is computed, it is applied to the state objects.
9076 *
9077 * @param networkRequests the nri objects to evaluate for possible network reassignment
9078 * @return NetworkReassignment listing of proposed network assignment changes
9079 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009080 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009081 private NetworkReassignment computeNetworkReassignment(
9082 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009083 final NetworkReassignment changes = new NetworkReassignment();
9084
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009085 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009086 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009087 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009088 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009089 }
Chalard Jean857a1712019-12-10 21:08:07 +09009090
James Mattisa076c532020-12-02 14:12:41 -08009091 for (final NetworkRequestInfo nri : networkRequests) {
9092 // Non-multilayer listen requests can be ignored.
9093 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9094 continue;
9095 }
9096 NetworkAgentInfo bestNetwork = null;
9097 NetworkRequest bestRequest = null;
9098 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009099 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009100 // Stop evaluating as the highest possible priority request is satisfied.
9101 if (null != bestNetwork) {
9102 bestRequest = req;
9103 break;
9104 }
9105 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009106 if (null == bestNetwork && isDefaultBlocked(nri)) {
9107 // Remove default networking if disallowed for managed default requests.
9108 bestNetwork = mNoServiceNetwork;
9109 }
9110 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009111 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009112 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009113 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009114 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009115 }
9116 return changes;
9117 }
9118
James Mattisa076c532020-12-02 14:12:41 -08009119 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9120 return new HashSet<>(mNetworkRequests.values());
9121 }
9122
Paul Jensenc88b39b2015-06-16 14:27:36 -04009123 /**
James Mattisa076c532020-12-02 14:12:41 -08009124 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009125 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009126 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009127 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009128 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9129 }
9130
9131 /**
9132 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9133 * being disconnected.
9134 */
9135 private void rematchNetworksAndRequests(
9136 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9137 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009138 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009139 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009140 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009141 final long computed = SystemClock.elapsedRealtime();
9142 applyNetworkReassignment(changes, start);
9143 final long applied = SystemClock.elapsedRealtime();
9144 issueNetworkNeeds();
9145 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009146 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009147 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9148 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009149 log(changes.debugString());
9150 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009151 // Shorter form, only one line of log
9152 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9153 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009154 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009155 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009156
Chalard Jeand7f762d2019-12-10 19:01:29 +09009157 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009158 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009159 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009160
9161 // Since most of the time there are only 0 or 1 background networks, it would probably
9162 // be more efficient to just use an ArrayList here. TODO : measure performance
9163 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9164 for (final NetworkAgentInfo nai : nais) {
9165 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9166 }
9167
Chalard Jeand7f762d2019-12-10 19:01:29 +09009168 // First, update the lists of satisfied requests in the network agents. This is necessary
9169 // because some code later depends on this state to be correct, most prominently computing
9170 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009171 for (final NetworkReassignment.RequestReassignment event :
9172 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009173 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9174 event.mOldNetworkRequest, event.mNewNetworkRequest,
9175 event.mOldNetwork, event.mNewNetwork,
9176 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009177 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009178
James Mattise3ef1912020-12-20 11:09:58 -08009179 // Process default network changes if applicable.
9180 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009181
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009182 // Notify requested networks are available after the default net is switched, but
9183 // before LegacyTypeTracker sends legacy broadcasts
9184 for (final NetworkReassignment.RequestReassignment event :
9185 changes.getRequestReassignments()) {
9186 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009187 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009188 } else {
James Mattisa076c532020-12-02 14:12:41 -08009189 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009190 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009191 }
9192 }
9193
junyulai0ac374f2020-12-14 18:41:52 +08009194 // Update the inactivity state before processing listen callbacks, because the background
9195 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009196 // just yet though, because they have to be sent after the listens are processed to keep
9197 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009198 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009199 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009200 // Rematching may have altered the inactivity state of some networks, so update all
9201 // inactivity timers. updateInactivityState reads the state from the network agent
9202 // and does nothing if the state has not changed : the source of truth is controlled
9203 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9204 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009205 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009206 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009207 }
9208 }
9209
Chalard Jeanb10ab412019-12-11 14:12:30 +09009210 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009211 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009212 // Process listen requests and update capabilities if the background state has
9213 // changed for this network. For consistency with previous behavior, send onLost
9214 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009215 processNewlyLostListenRequests(nai);
9216 if (oldBackground != nai.isBackgroundNetwork()) {
9217 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009218 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009219 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009220 }
9221
junyulai0ac374f2020-12-14 18:41:52 +08009222 for (final NetworkAgentInfo nai : inactiveNetworks) {
9223 // For nascent networks, if connecting with no foreground request, skip broadcasting
9224 // LOSING for backward compatibility. This is typical when mobile data connected while
9225 // wifi connected with mobile data always-on enabled.
9226 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009227 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009228 }
9229
James Mattise3ef1912020-12-20 11:09:58 -08009230 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009231
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009232 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009233 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009234 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009235 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009236 // This network has active linger timers and no requests, but is not
9237 // lingering. Linger it.
9238 //
9239 // One way (the only way?) this can happen if this network is unvalidated
9240 // and became unneeded due to another network improving its score to the
9241 // point where this network will no longer be able to satisfy any requests
9242 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009243 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009244 notifyNetworkLosing(nai, now);
9245 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009246 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009247 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009248 teardownUnneededNetwork(nai);
9249 }
9250 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009251 }
9252 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009253
Chalard Jean62edfd82019-12-02 18:39:29 +09009254 /**
9255 * Apply a change in background state resulting from rematching networks with requests.
9256 *
9257 * During rematch, a network may change background states by starting to satisfy or stopping
9258 * to satisfy a foreground request. Listens don't count for this. When a network changes
9259 * background states, its capabilities need to be updated and callbacks fired for the
9260 * capability change.
9261 *
9262 * @param nai The network that changed background states
9263 */
9264 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9265 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9266 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9267 updateNetworkPermissions(nai, newNc);
9268 nai.getAndSetNetworkCapabilities(newNc);
9269 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9270 }
9271
Chalard Jeanf0344532019-11-19 19:23:38 +09009272 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009273 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009274 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009275 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9276 changes.getReassignment(mDefaultRequest);
9277 final NetworkAgentInfo oldDefaultNetwork =
9278 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9279 final NetworkAgentInfo newDefaultNetwork =
9280 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009281
Chalard Jean5b409c72021-02-04 13:12:59 +09009282 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009283 // Maintain the illusion : since the legacy API only understands one network at a time,
9284 // if the default network changed, apps should see a disconnected broadcast for the
9285 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009286 if (oldDefaultNetwork != null) {
9287 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9288 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009289 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009290 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009291 // The new default network can be newly null if and only if the old default
9292 // network doesn't satisfy the default request any more because it lost a
9293 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009294 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009295 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009296 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009297 }
9298 }
9299
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009300 // Now that all the callbacks have been sent, send the legacy network broadcasts
9301 // as needed. This is necessary so that legacy requests correctly bind dns
9302 // requests to this network. The legacy users are listening for this broadcast
9303 // and will generally do a dns request so they can ensureRouteToHost and if
9304 // they do that before the callbacks happen they'll use the default network.
9305 //
9306 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9307 // callbacks, but if apps can receive the broadcast before the callback, they still might
9308 // have an inconsistent view of networking.
9309 //
9310 // This *does* introduce a race where if the user uses the new api
9311 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9312 // they may get old info. Reverse this after the old startUsing api is removed.
9313 // This is on top of the multiple intent sequencing referenced in the todo above.
9314 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009315 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009316 addNetworkToLegacyTypeTracker(nai);
9317 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009318 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009319 }
9320
Chalard Jean0354d8c2021-01-12 10:58:56 +09009321 private void issueNetworkNeeds() {
9322 ensureRunningOnConnectivityServiceThread();
9323 for (final NetworkOfferInfo noi : mNetworkOffers) {
9324 issueNetworkNeeds(noi);
9325 }
9326 }
9327
9328 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9329 ensureRunningOnConnectivityServiceThread();
9330 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9331 informOffer(nri, noi.offer, mNetworkRanker);
9332 }
9333 }
9334
9335 /**
9336 * Inform a NetworkOffer about any new situation of a request.
9337 *
9338 * This function handles updates to offers. A number of events may happen that require
9339 * updating the registrant for this offer about the situation :
9340 * • The offer itself was updated. This may lead the offer to no longer being able
9341 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9342 * or conversely being strengthened enough to beat the satisfier (and therefore
9343 * start being needed)
9344 * • The network satisfying a request changed (including cases where the request
9345 * starts or stops being satisfied). The new network may be a stronger or weaker
9346 * match than the old one, possibly affecting whether the offer is needed.
9347 * • The network satisfying a request updated their score. This may lead the offer
9348 * to no longer be able to beat it if the current satisfier got better, or
9349 * conversely start being a good choice if the current satisfier got weaker.
9350 *
9351 * @param nri The request
9352 * @param offer The offer. This may be an updated offer.
9353 */
9354 private static void informOffer(@NonNull NetworkRequestInfo nri,
9355 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9356 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9357 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009358
9359 // Multi-layer requests have a currently active request, the one being satisfied.
9360 // Since the system will try to bring up a better network than is currently satisfying
9361 // the request, NetworkProviders need to be told the offers matching the requests *above*
9362 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9363 // not needed, and the offer is needed for the active request iff the offer can beat
9364 // the satisfier.
9365 // For non-multilayer requests, the logic above gracefully degenerates to only the
9366 // last case.
9367 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9368 // providers that the offer is needed for this request, until the active request is found.
9369 // In a second phase, deal with the currently active request. In a third phase, inform
9370 // the providers that offer is unneeded for the remaining requests.
9371
9372 // First phase : inform providers of all requests above the active request.
9373 int i;
9374 for (i = 0; nri.mRequests.size() > i; ++i) {
9375 final NetworkRequest request = nri.mRequests.get(i);
9376 if (activeRequest == request) break; // Found the active request : go to phase 2
9377 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9378 // Since this request is higher-priority than the one currently satisfied, if the
9379 // offer can satisfy it, the provider should try and bring up the network for sure ;
9380 // no need to even ask the ranker – an offer that can satisfy is always better than
9381 // no network. Hence tell the provider so unless it already knew.
9382 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9383 offer.onNetworkNeeded(request);
9384 }
9385 }
9386
9387 // Second phase : deal with the active request (if any)
9388 if (null != activeRequest && activeRequest.isRequest()) {
9389 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009390 // If an offer can satisfy the request, it is considered needed if it is currently
9391 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009392 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009393 && satisfier.factorySerialNumber == offer.providerId
9394 && activeRequest.canBeSatisfiedBy(offer.caps);
9395 final boolean newNeeded = currentlyServing
9396 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009397 if (newNeeded != oldNeeded) {
9398 if (newNeeded) {
9399 offer.onNetworkNeeded(activeRequest);
9400 } else {
9401 // The offer used to be able to beat the satisfier. Now it can't.
9402 offer.onNetworkUnneeded(activeRequest);
9403 }
9404 }
9405 }
9406
9407 // Third phase : inform the providers that the offer isn't needed for any request
9408 // below the active one.
9409 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9410 final NetworkRequest request = nri.mRequests.get(i);
9411 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9412 // Since this request is lower-priority than the one currently satisfied, if the
9413 // offer can satisfy it, the provider should not try and bring up the network.
9414 // Hence tell the provider so unless it already knew.
9415 if (offer.neededFor(request)) {
9416 offer.onNetworkUnneeded(request);
9417 }
9418 }
9419 }
9420
Chalard Jean61c79252019-11-07 23:07:32 +09009421 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9422 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9423 NetworkRequest nr = nai.requestAt(i);
9424 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9425 // legacy type tracker filters out repeat adds
9426 mLegacyTypeTracker.add(nr.legacyType, nai);
9427 }
9428 }
9429
9430 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009431 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009432 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9433 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9434 if (nai.isVPN()) {
9435 mLegacyTypeTracker.add(TYPE_VPN, nai);
9436 }
9437 }
9438
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009439 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009440 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009441 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009442 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009443 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009444 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009445
Chalard Jean254bd162022-08-25 13:04:51 +09009446 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009447 // Don't repeat publish.
9448 if (newInetCondition == mDefaultInetConditionPublished) return;
9449
9450 mDefaultInetConditionPublished = newInetCondition;
9451 sendInetConditionBroadcast(nai.networkInfo);
9452 }
9453
Chalard Jeand61375d2020-01-14 22:46:36 +09009454 @NonNull
9455 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9456 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009457 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009458 final boolean suspended =
9459 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9460 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9461 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9462 // state. This is because the network could have been suspended before connecting,
9463 // or it could be disconnecting while being suspended, and in both these cases
9464 // the state should not be overridden. Note that the only detailed state that
9465 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9466 // worry about multiple different substates of CONNECTED.
9467 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9468 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009469 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9470 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9471 // network agent is created, then goes to suspended, then goes out of suspended without
9472 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009473 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009474 ? NetworkInfo.DetailedState.CONNECTED
9475 : NetworkInfo.DetailedState.CONNECTING,
9476 info.getReason(),
9477 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009478 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009479 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009480 return newInfo;
9481 }
9482
9483 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9484 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9485
Erik Kline99f301b2017-02-15 19:59:17 +09009486 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009487 NetworkInfo oldInfo = null;
9488 synchronized (networkAgent) {
9489 oldInfo = networkAgent.networkInfo;
9490 networkAgent.networkInfo = newInfo;
9491 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009492
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009493 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009494 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9495 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009496 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009497
Chalard Jean254bd162022-08-25 13:04:51 +09009498 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009499 && (state == NetworkInfo.State.CONNECTED
9500 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009501
9502 // A network that has just connected has zero requests and is thus a foreground network.
9503 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9504
Luke Huangfdd11f82019-04-09 18:41:49 +08009505 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009506 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009507 // Initialize the network's capabilities to their starting values according to the
9508 // underlying networks. This ensures that the capabilities are correct before
9509 // anything happens to the network.
9510 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009511 }
Chalard Jean254bd162022-08-25 13:04:51 +09009512 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009513 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009514 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009515 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009516 }
9517
Chalard Jean254bd162022-08-25 13:04:51 +09009518 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9519 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009520
lucaslin45e639b2019-04-03 17:09:28 +08009521 // NetworkCapabilities need to be set before sending the private DNS config to
9522 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009523 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9524
Erik Kline9a62f012018-03-21 07:18:33 -07009525 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009526 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9527 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009528
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009529 // If a rate limit has been configured and is applicable to this network (network
9530 // provides internet connectivity), apply it. The tc police filter cannot be attached
9531 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9532 // updateInterfaces -> INetd#networkAddInterface.
9533 // Note: in case of a system server crash, the NetworkController constructor in netd
9534 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9535 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9536 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9537 mIngressRateLimit);
9538 }
9539
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009540 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9541 // command must be sent after updating LinkProperties to maximize chances of
9542 // NetworkMonitor seeing the correct LinkProperties when starting.
9543 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009544 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009545 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009546 }
Chalard Jeand4900722022-02-06 12:25:38 +09009547 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9548 params.networkAgentConfig = networkAgent.networkAgentConfig;
9549 params.networkCapabilities = networkAgent.networkCapabilities;
9550 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9551 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009552 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9553 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9554 // call that would cause a Log.wtf to be emitted from the system_server process, and
9555 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9556 // process to check the interface version, just use an SDK check. NetworkStack will
9557 // always be new enough when running on T+.
9558 if (SdkLevel.isAtLeastT()) {
9559 networkAgent.networkMonitor().notifyNetworkConnected(params);
9560 } else {
9561 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9562 params.networkCapabilities);
9563 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009564 final long delay = activelyPreferBadWifi()
9565 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9566 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9567 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009568
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009569 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9570 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9571 // capabilities, so it only needs to be done once on initial connect, not every time the
9572 // network's capabilities change. Note that we do this before rematching the network,
9573 // so we could decide to tear it down immediately afterwards. That's fine though - on
9574 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9575 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009576 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009577
junyulai0ac374f2020-12-14 18:41:52 +08009578 // Before first rematching networks, put an inactivity timer without any request, this
9579 // allows {@code updateInactivityState} to update the state accordingly and prevent
9580 // tearing down for any {@code unneeded} evaluation in this period.
9581 // Note that the timer will not be rescheduled since the expiry time is
9582 // fixed after connection regardless of the network satisfying other requests or not.
9583 // But it will be removed as soon as the network satisfies a request for the first time.
9584 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9585 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009586 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009587
Paul Jensen05e85ee2014-09-11 11:00:39 -04009588 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009589 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009590
9591 // This has to happen after matching the requests, because callbacks are just requests.
9592 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009593 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009594 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009595 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009596 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009597 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009598 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009599 if (networkAgent.isVPN()) {
9600 // As the active or bound network changes for apps, broadcast the default proxy, as
9601 // apps may need to update their proxy data. This is called after disconnecting from
9602 // VPN to make sure we do not broadcast the old proxy data.
9603 // TODO(b/122649188): send the broadcast only to VPN users.
9604 mProxyTracker.sendProxyBroadcast();
9605 }
Chalard Jean254bd162022-08-25 13:04:51 +09009606 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9607 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009608 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009609 }
9610 }
9611
Chalard Jean28018572020-12-21 18:36:52 +09009612 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009613 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9614 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009615 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009616 }
9617
Erik Kline99f301b2017-02-15 19:59:17 +09009618 // Notify only this one new request of the current state. Transfer all the
9619 // current state by calling NetworkCapabilities and LinkProperties callbacks
9620 // so that callers can be guaranteed to have as close to atomicity in state
9621 // transfer as can be supported by this current API.
9622 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009623 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009624 if (nri.mPendingIntent != null) {
9625 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9626 // Attempt no subsequent state pushes where intents are involved.
9627 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009628 }
Erik Kline99f301b2017-02-15 19:59:17 +09009629
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009630 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009631 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009632 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9633 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9634 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009635 }
9636
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009637 // Notify the requests on this NAI that the network is now lingered.
9638 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009639 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009640 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9641 }
9642
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009643 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9644 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9645 return vpnBlocked
9646 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9647 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9648 }
9649
9650 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9651 if (blockedReasons == BLOCKED_REASON_NONE) {
9652 mUidBlockedReasons.delete(uid);
9653 } else {
9654 mUidBlockedReasons.put(uid, blockedReasons);
9655 }
9656 }
9657
junyulaif2c67e42018-08-07 19:50:45 +08009658 /**
9659 * Notify of the blocked state apps with a registered callback matching a given NAI.
9660 *
9661 * Unlike other callbacks, blocked status is different between each individual uid. So for
9662 * any given nai, all requests need to be considered according to the uid who filed it.
9663 *
9664 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009665 * @param oldMetered True if the previous network capabilities were metered.
9666 * @param newMetered True if the current network capabilities are metered.
9667 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9668 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009669 */
9670 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009671 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9672 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009673
9674 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9675 NetworkRequest nr = nai.requestAt(i);
9676 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009677
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009678 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9679 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9680 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009681 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009682 : oldVpnBlocked;
9683
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009684 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9685 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9686 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009687 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009688 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009689 }
9690 }
9691 }
9692
9693 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009694 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009695 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009696 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009697 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009698 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009699 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009700 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009701 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009702
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009703 final int oldBlockedState = getBlockedState(
9704 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9705 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9706 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009707 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009708 }
junyulaif2c67e42018-08-07 19:50:45 +08009709 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9710 NetworkRequest nr = nai.requestAt(i);
9711 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009712 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009713 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9714 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009715 }
9716 }
9717 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009718 }
9719
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009720 @VisibleForTesting
9721 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009722 // The NetworkInfo we actually send out has no bearing on the real
9723 // state of affairs. For example, if the default connection is mobile,
9724 // and a request for HIPRI has just gone away, we need to pretend that
9725 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9726 // the state to DISCONNECTED, even though the network is of type MOBILE
9727 // and is still connected.
9728 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9729 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009730 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009731 if (state != DetailedState.DISCONNECTED) {
9732 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009733 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009734 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009735 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009736 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9737 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9738 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9739 if (info.isFailover()) {
9740 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9741 nai.networkInfo.setFailover(false);
9742 }
9743 if (info.getReason() != null) {
9744 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9745 }
9746 if (info.getExtraInfo() != null) {
9747 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9748 }
9749 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009750 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009751 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009752 if (newDefaultAgent != null) {
9753 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9754 newDefaultAgent.networkInfo);
9755 } else {
9756 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9757 }
9758 }
9759 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9760 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009761 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009762 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009763 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009764 }
9765 }
9766 }
9767
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009768 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009769 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009770 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009771 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009772 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009773 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9774 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009775 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9776 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009777 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009778 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009779 } else {
9780 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9781 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009782 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009783 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009784
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009785 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9786 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9787 }
9788
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009789 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009790 * Returns the list of all interfaces that could be used by network traffic that does not
9791 * explicitly specify a network. This includes the default network, but also all VPNs that are
9792 * currently connected.
9793 *
9794 * Must be called on the handler thread.
9795 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009796 @NonNull
9797 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009798 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009799 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009800 final Set<Integer> activeNetIds = new ArraySet<>();
9801 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9802 if (nri.isBeingSatisfied()) {
9803 activeNetIds.add(nri.getSatisfier().network().netId);
9804 }
9805 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009806 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009807 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009808 defaultNetworks.add(nai.network);
9809 }
9810 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009811 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009812 }
9813
9814 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009815 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9816 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009817 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009818 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009819 ensureRunningOnConnectivityServiceThread();
9820 String activeIface = null;
9821 LinkProperties activeLinkProperties = getActiveLinkProperties();
9822 if (activeLinkProperties != null) {
9823 activeIface = activeLinkProperties.getInterfaceName();
9824 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009825
junyulai2050bed2021-01-23 09:46:34 +08009826 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009827 try {
junyulaide41fc22021-01-22 22:46:01 +08009828 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009829 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009830 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9831 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009832 } catch (Exception ignored) {
9833 }
9834 }
9835
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009836 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009837 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009838 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009839 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009840 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009841
9842 if (!TextUtils.isEmpty(settingUrl)) {
9843 return settingUrl;
9844 }
9845
9846 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009847 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009848 if (!TextUtils.isEmpty(settingUrl)) {
9849 return settingUrl;
9850 }
9851
9852 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009853 }
9854
9855 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009856 public void startNattKeepalive(Network network, int intervalSeconds,
9857 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009858 enforceKeepalivePermission();
9859 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009860 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00009861 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
9862 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
9863 // false because there is no way and no plan to configure automaticOnOffKeepalives
9864 // in this deprecated method.
9865 false /* automaticOnOffKeepalives */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009866 }
9867
9868 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009869 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009870 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00009871 String dstAddr, boolean automaticOnOffKeepalives) {
Josh Gao461a1222020-06-16 15:58:11 -07009872 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009873 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009874 mKeepaliveTracker.startNattKeepalive(
9875 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9876 intervalSeconds, cb,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00009877 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT, automaticOnOffKeepalives);
Josh Gao461a1222020-06-16 15:58:11 -07009878 } finally {
9879 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9880 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009881 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9882 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009883 }
9884 }
junyulaid05a1922019-01-15 11:32:44 +08009885 }
9886
9887 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009888 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009889 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009890 try {
9891 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009892 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009893 mKeepaliveTracker.startTcpKeepalive(
9894 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9895 } finally {
9896 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9897 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009898 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9899 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009900 }
9901 }
junyulai0835a1e2019-01-08 20:04:33 +08009902 }
9903
9904 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +09009905 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009906 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +09009907 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
9908 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009909 }
9910
9911 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009912 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009913 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009914
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009915 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009916 final long token = Binder.clearCallingIdentity();
9917 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009918 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9919 UserHandle.getUserHandleForUid(uid))) {
9920 return;
9921 }
9922
Heemin Seogdb8489d2019-06-12 09:21:44 -07009923 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9924 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009925
9926 // Turn airplane mode off
9927 setAirplaneMode(false);
9928
9929 // restore private DNS settings to default mode (opportunistic)
9930 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9931 UserHandle.getUserHandleForUid(uid))) {
9932 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9933 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9934 }
9935
9936 Settings.Global.putString(mContext.getContentResolver(),
9937 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009938 } finally {
9939 Binder.restoreCallingIdentity(token);
9940 }
Stuart Scottd5463642015-04-02 18:00:02 -07009941 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009942
Ricky Wai7097cc92018-01-23 04:09:45 +00009943 @Override
9944 public byte[] getNetworkWatchlistConfigHash() {
9945 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9946 if (nwm == null) {
9947 loge("Unable to get NetworkWatchlistManager");
9948 return null;
9949 }
9950 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9951 return nwm.getWatchlistConfigHash();
9952 }
9953
Hugo Benichibe0c7652016-05-31 16:28:06 +09009954 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009955 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009956 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009957 }
Hugo Benichif4210292017-04-21 15:07:12 +09009958
9959 private static boolean toBool(int encodedBoolean) {
9960 return encodedBoolean != 0; // Only 0 means false.
9961 }
9962
9963 private static int encodeBool(boolean b) {
9964 return b ? 1 : 0;
9965 }
mswest4632928412018-03-12 10:34:34 -07009966
9967 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009968 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9969 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9970 @NonNull String[] args) {
9971 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9972 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009973 }
9974
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009975 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009976 @Override
9977 public int onCommand(String cmd) {
9978 if (cmd == null) {
9979 return handleDefaultCommands(cmd);
9980 }
9981 final PrintWriter pw = getOutPrintWriter();
9982 try {
9983 switch (cmd) {
9984 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009985 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
9986 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -07009987 final String action = getNextArg();
9988 if ("enable".equals(action)) {
9989 setAirplaneMode(true);
9990 return 0;
9991 } else if ("disable".equals(action)) {
9992 setAirplaneMode(false);
9993 return 0;
9994 } else if (action == null) {
9995 final ContentResolver cr = mContext.getContentResolver();
9996 final int enabled = Settings.Global.getInt(cr,
9997 Settings.Global.AIRPLANE_MODE_ON);
9998 pw.println(enabled == 0 ? "disabled" : "enabled");
9999 return 0;
10000 } else {
10001 onHelp();
10002 return -1;
10003 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010004 case "reevaluate":
10005 // Usage : adb shell cmd connectivity reevaluate <netId>
10006 // If netId is omitted, then reevaluate the default network
10007 final String netId = getNextArg();
10008 final NetworkAgentInfo nai;
10009 if (null == netId) {
10010 // Note that the command is running on the wrong thread to call this,
10011 // so this could in principle return stale data. But it can't crash.
10012 nai = getDefaultNetwork();
10013 } else {
10014 // If netId can't be parsed, this throws NumberFormatException, which
10015 // is passed back to adb who prints it.
10016 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10017 }
10018 if (null == nai) {
10019 pw.println("Unknown network (net ID not found or no default network)");
10020 return 0;
10021 }
10022 Log.d(TAG, "Reevaluating network " + nai.network);
10023 reportNetworkConnectivity(nai.network, !nai.isValidated());
10024 return 0;
mswest4632928412018-03-12 10:34:34 -070010025 default:
10026 return handleDefaultCommands(cmd);
10027 }
10028 } catch (Exception e) {
10029 pw.println(e);
10030 }
10031 return -1;
10032 }
10033
10034 @Override
10035 public void onHelp() {
10036 PrintWriter pw = getOutPrintWriter();
10037 pw.println("Connectivity service commands:");
10038 pw.println(" help");
10039 pw.println(" Print this help text.");
10040 pw.println(" airplane-mode [enable|disable]");
10041 pw.println(" Turn airplane mode on or off.");
10042 pw.println(" airplane-mode");
10043 pw.println(" Get airplane mode.");
10044 }
10045 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010046
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010047 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010048 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10049 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10050 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010051 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010052 }
10053
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010054 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10055 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010056 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10057 final TransportInfo newInfo = nc.getTransportInfo();
10058 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10059 return;
10060 }
10061 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010062 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010063 }
10064 }
10065
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010066 /**
10067 * @param connectionInfo the connection to resolve.
10068 * @return {@code uid} if the connection is found and the app has permission to observe it
10069 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10070 * connection is not found.
10071 */
10072 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010073 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10074 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10075 }
10076
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010077 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010078 connectionInfo.local, connectionInfo.remote);
10079
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010080 if (uid == INVALID_UID) return uid; // Not found.
10081
10082 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10083 // VPN, if any, that applies to the UID that owns the connection.
10084 if (checkNetworkStackPermission()) return uid;
10085
10086 final NetworkAgentInfo vpn = getVpnForUid(uid);
10087 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010088 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010089 return INVALID_UID;
10090 }
10091
10092 return uid;
10093 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010094
Benedict Wong493e04b2018-11-09 14:45:34 -080010095 /**
10096 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10097 *
10098 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10099 */
10100 @Override
10101 public IBinder startOrGetTestNetworkService() {
10102 synchronized (mTNSLock) {
10103 TestNetworkService.enforceTestNetworkPermissions(mContext);
10104
10105 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010106 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010107 }
10108
10109 return mTNS;
10110 }
10111 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010112
Cody Kesting73708bf2019-12-18 10:57:50 -080010113 /**
10114 * Handler used for managing all Connectivity Diagnostics related functions.
10115 *
10116 * @see android.net.ConnectivityDiagnosticsManager
10117 *
10118 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10119 */
10120 @VisibleForTesting
10121 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010122 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10123
Cody Kesting73708bf2019-12-18 10:57:50 -080010124 /**
10125 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10126 * android.net.ConnectivityDiagnosticsManager}.
10127 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10128 * NetworkRequestInfo to be registered
10129 */
10130 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10131
10132 /**
10133 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10134 * android.net.ConnectivityDiagnosticsManager}.
10135 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10136 * arg1 = the uid of the caller
10137 */
10138 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10139
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010140 /**
10141 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010142 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010143 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10144 * NetworkMonitor.
10145 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010146 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010147 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010148
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010149 /**
10150 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10151 * been detected on the network.
10152 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10153 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10154 * arg2 = NetID.
10155 * data = PersistableBundle of extras passed from NetworkMonitor.
10156 */
10157 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10158
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010159 /**
10160 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10161 * the platform. This event will invoke {@link
10162 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10163 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010164 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010165 */
10166 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10167
Cody Kesting73708bf2019-12-18 10:57:50 -080010168 private ConnectivityDiagnosticsHandler(Looper looper) {
10169 super(looper);
10170 }
10171
10172 @Override
10173 public void handleMessage(Message msg) {
10174 switch (msg.what) {
10175 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10176 handleRegisterConnectivityDiagnosticsCallback(
10177 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10178 break;
10179 }
10180 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10181 handleUnregisterConnectivityDiagnosticsCallback(
10182 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10183 break;
10184 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010185 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010186 final ConnectivityReportEvent reportEvent =
10187 (ConnectivityReportEvent) msg.obj;
10188
Aaron Huang959d3642021-01-21 15:47:41 +080010189 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010190 break;
10191 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010192 case EVENT_DATA_STALL_SUSPECTED: {
10193 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010194 final Pair<Long, PersistableBundle> arg =
10195 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010196 if (nai == null) break;
10197
Aaron Huang959d3642021-01-21 15:47:41 +080010198 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010199 break;
10200 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010201 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010202 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010203 break;
10204 }
10205 default: {
10206 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10207 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010208 }
10209 }
10210 }
10211
10212 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10213 @VisibleForTesting
10214 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10215 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10216 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010217 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010218
10219 @VisibleForTesting
10220 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010221 @NonNull IConnectivityDiagnosticsCallback cb,
10222 @NonNull NetworkRequestInfo nri,
10223 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010224 mCb = cb;
10225 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010226 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010227 }
10228
10229 @Override
10230 public void binderDied() {
10231 log("ConnectivityDiagnosticsCallback IBinder died.");
10232 unregisterConnectivityDiagnosticsCallback(mCb);
10233 }
10234 }
10235
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010236 /**
10237 * Class used for sending information from {@link
10238 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10239 */
10240 private static class NetworkTestedResults {
10241 private final int mNetId;
10242 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010243 @Nullable private final String mRedirectUrl;
10244
10245 private NetworkTestedResults(
10246 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10247 mNetId = netId;
10248 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010249 mRedirectUrl = redirectUrl;
10250 }
10251 }
10252
10253 /**
10254 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10255 * ConnectivityDiagnosticsHandler}.
10256 */
10257 private static class ConnectivityReportEvent {
10258 private final long mTimestampMillis;
10259 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010260 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010261
Aaron Huang959d3642021-01-21 15:47:41 +080010262 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10263 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010264 mTimestampMillis = timestampMillis;
10265 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010266 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010267 }
10268 }
10269
Cody Kestingf1120be2020-08-03 18:01:40 -070010270 /**
10271 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10272 * ConnectivityDiagnosticsHandler}.
10273 */
10274 private static class ReportedNetworkConnectivityInfo {
10275 public final boolean hasConnectivity;
10276 public final boolean isNetworkRevalidating;
10277 public final int reporterUid;
10278 @NonNull public final NetworkAgentInfo nai;
10279
10280 private ReportedNetworkConnectivityInfo(
10281 boolean hasConnectivity,
10282 boolean isNetworkRevalidating,
10283 int reporterUid,
10284 @NonNull NetworkAgentInfo nai) {
10285 this.hasConnectivity = hasConnectivity;
10286 this.isNetworkRevalidating = isNetworkRevalidating;
10287 this.reporterUid = reporterUid;
10288 this.nai = nai;
10289 }
10290 }
10291
Cody Kesting73708bf2019-12-18 10:57:50 -080010292 private void handleRegisterConnectivityDiagnosticsCallback(
10293 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10294 ensureRunningOnConnectivityServiceThread();
10295
10296 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010297 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010298 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10299
James Mattis64b8b0f2020-11-24 17:40:49 -080010300 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10301 // confusing for these networks to change when an NRI is satisfied in another layer.
10302 if (nri.isMultilayerRequest()) {
10303 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10304 + "network requests.");
10305 }
10306
Cody Kesting73708bf2019-12-18 10:57:50 -080010307 // This means that the client registered the same callback multiple times. Do
10308 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010309 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010310 if (VDBG) log("Diagnostics callback is already registered");
10311
10312 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10313 // incremented when the NetworkRequestInfo is created as part of
10314 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010315 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010316 return;
10317 }
10318
Cody Kesting31f1ff62020-03-05 10:46:02 -080010319 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010320
10321 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010322 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010323 } catch (RemoteException e) {
10324 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010325 return;
10326 }
10327
10328 // Once registered, provide ConnectivityReports for matching Networks
10329 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10330 synchronized (mNetworkForNetId) {
10331 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10332 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010333 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10334 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010335 matchingNetworks.add(nai);
10336 }
10337 }
10338 }
10339 for (final NetworkAgentInfo nai : matchingNetworks) {
10340 final ConnectivityReport report = nai.getConnectivityReport();
10341 if (report == null) {
10342 continue;
10343 }
10344 if (!checkConnectivityDiagnosticsPermissions(
10345 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10346 continue;
10347 }
10348
10349 try {
10350 cb.onConnectivityReportAvailable(report);
10351 } catch (RemoteException e) {
10352 // Exception while sending the ConnectivityReport. Move on to the next network.
10353 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010354 }
10355 }
10356
10357 private void handleUnregisterConnectivityDiagnosticsCallback(
10358 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10359 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010360 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010361
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010362 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10363 mConnectivityDiagnosticsCallbacks.remove(iCb);
10364 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010365 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10366 return;
10367 }
10368
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010369 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010370
Cody Kesting70fa2b22020-12-02 12:16:56 -080010371 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10372 // (if the Binder died)
10373 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10374 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010375 return;
10376 }
10377
Cody Kesting46cb1672020-03-04 13:35:20 -080010378 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10379 // incremented when the NetworkRequestInfo is created as part of
10380 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010381 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010382
Cody Kesting31f1ff62020-03-05 10:46:02 -080010383 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010384 }
10385
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010386 private void handleNetworkTestedWithExtras(
10387 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10388 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010389 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010390 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010391 final ConnectivityReport report =
10392 new ConnectivityReport(
10393 reportEvent.mNai.network,
10394 reportEvent.mTimestampMillis,
10395 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010396 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010397 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010398 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010399
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010400 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010401 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010402 for (final IConnectivityDiagnosticsCallback cb : results) {
10403 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010404 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010405 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010406 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010407 }
10408 }
10409 }
10410
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010411 private void handleDataStallSuspected(
10412 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10413 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010414 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010415 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010416 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010417 new DataStallReport(
10418 nai.network,
10419 timestampMillis,
10420 detectionMethod,
10421 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010422 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010423 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010424 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010425 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010426 for (final IConnectivityDiagnosticsCallback cb : results) {
10427 try {
10428 cb.onDataStallSuspected(report);
10429 } catch (RemoteException ex) {
10430 loge("Error invoking onDataStallSuspected", ex);
10431 }
10432 }
10433 }
10434
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010435 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010436 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10437 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10438 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10439
10440 // If the Network is being re-validated as a result of this call to
10441 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10442 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010443 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010444 getMatchingPermissionedCallbacks(
10445 nai,
10446 reportedNetworkConnectivityInfo.isNetworkRevalidating
10447 ? Process.INVALID_UID
10448 : reportedNetworkConnectivityInfo.reporterUid);
10449
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010450 for (final IConnectivityDiagnosticsCallback cb : results) {
10451 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010452 cb.onNetworkConnectivityReported(
10453 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010454 } catch (RemoteException ex) {
10455 loge("Error invoking onNetworkConnectivityReported", ex);
10456 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010457
10458 // If the Network isn't re-validating, also provide the cached report. If there is no
10459 // cached report, the Network is still being validated and a report will be sent once
10460 // validation is complete. Note that networks which never undergo validation will still
10461 // have a cached ConnectivityReport with RESULT_SKIPPED.
10462 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10463 try {
10464 cb.onConnectivityReportAvailable(cachedReport);
10465 } catch (RemoteException ex) {
10466 loge("Error invoking onConnectivityReportAvailable", ex);
10467 }
10468 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010469 }
10470 }
10471
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010472 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010473 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10474 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010475 sanitized.setUids(null);
10476 sanitized.setAdministratorUids(new int[0]);
10477 sanitized.setOwnerUid(Process.INVALID_UID);
10478 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010479 }
10480
Cody Kestingf1120be2020-08-03 18:01:40 -070010481 /**
10482 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10483 *
10484 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10485 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010486 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010487 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010488 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010489 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010490 mConnectivityDiagnosticsCallbacks.entrySet()) {
10491 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10492 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010493
James Mattis64b8b0f2020-11-24 17:40:49 -080010494 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010495 if (!nai.satisfies(nri.mRequests.get(0))) {
10496 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010497 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010498
10499 // UID for this callback must either be:
10500 // - INVALID_UID (which sends callbacks to all UIDs), or
10501 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10502 // notified as a result)
10503 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10504 continue;
10505 }
10506
10507 if (!checkConnectivityDiagnosticsPermissions(
10508 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10509 continue;
10510 }
10511
10512 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010513 }
10514 return results;
10515 }
10516
Cody Kesting7474f672021-05-11 14:22:40 -070010517 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10518 @NonNull NetworkAgentInfo nai) {
10519 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10520 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10521 }
10522
Cody Kesting160ef392021-05-05 13:17:22 -070010523 private boolean hasLocationPermission(String packageName, int uid) {
10524 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10525 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10526 // call in a try-catch.
10527 try {
10528 if (!mLocationPermissionChecker.checkLocationPermission(
10529 packageName, null /* featureId */, uid, null /* message */)) {
10530 return false;
10531 }
10532 } catch (SecurityException e) {
10533 return false;
10534 }
10535
10536 return true;
10537 }
10538
10539 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10540 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010541 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010542 && virtual.networkCapabilities.getOwnerUid() == uid
10543 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10544 return true;
10545 }
10546 }
10547
10548 return false;
10549 }
10550
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010551 @VisibleForTesting
10552 boolean checkConnectivityDiagnosticsPermissions(
10553 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10554 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10555 return true;
10556 }
10557
Cody Kesting160ef392021-05-05 13:17:22 -070010558 // Administrator UIDs also contains the Owner UID
10559 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10560 if (!CollectionUtils.contains(administratorUids, callbackUid)
10561 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010562 return false;
10563 }
10564
Cody Kesting7474f672021-05-11 14:22:40 -070010565 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10566 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010567 }
10568
Cody Kestingd199a9d2019-12-17 12:55:28 -080010569 @Override
10570 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010571 @NonNull IConnectivityDiagnosticsCallback callback,
10572 @NonNull NetworkRequest request,
10573 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010574 Objects.requireNonNull(callback, "callback must not be null");
10575 Objects.requireNonNull(request, "request must not be null");
10576 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10577
Cody Kesting73708bf2019-12-18 10:57:50 -080010578 if (request.legacyType != TYPE_NONE) {
10579 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10580 + " Please use NetworkCapabilities instead.");
10581 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010582 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010583 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010584
10585 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10586 // and administrator uids to be safe.
10587 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010588 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010589
10590 final NetworkRequest requestWithId =
10591 new NetworkRequest(
10592 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10593
10594 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10595 //
10596 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10597 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10598 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010599 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010600 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010601 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010602
10603 mConnectivityDiagnosticsHandler.sendMessage(
10604 mConnectivityDiagnosticsHandler.obtainMessage(
10605 ConnectivityDiagnosticsHandler
10606 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10607 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010608 }
10609
10610 @Override
10611 public void unregisterConnectivityDiagnosticsCallback(
10612 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010613 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010614 mConnectivityDiagnosticsHandler.sendMessage(
10615 mConnectivityDiagnosticsHandler.obtainMessage(
10616 ConnectivityDiagnosticsHandler
10617 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010618 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010619 0,
10620 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010621 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010622
10623 @Override
10624 public void simulateDataStall(int detectionMethod, long timestampMillis,
10625 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010626 Objects.requireNonNull(network, "network must not be null");
10627 Objects.requireNonNull(extras, "extras must not be null");
10628
paulhu3ffffe72021-09-16 10:15:22 +080010629 enforceAnyPermissionOf(mContext,
10630 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010631 android.Manifest.permission.NETWORK_STACK);
10632 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10633 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010634 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010635 }
10636
10637 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010638 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010639 throw new SecurityException("Data Stall simulation is only possible for network "
10640 + "creators");
10641 }
10642
Cody Kesting652e3ec2020-05-21 12:08:21 -070010643 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10644 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10645 // Data Stall information as a DataStallReportParcelable and passing to
10646 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10647 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010648 final DataStallReportParcelable p = new DataStallReportParcelable();
10649 p.timestampMillis = timestampMillis;
10650 p.detectionMethod = detectionMethod;
10651
10652 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10653 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10654 }
10655 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10656 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10657 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10658 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10659 }
10660
Serik Beketayevec8ad212020-12-07 22:43:07 -080010661 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010662 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010663
lucaslin66f44212021-02-23 01:12:55 +080010664 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10665 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010666 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010667 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010668 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010669 }
lucaslin37a16d92021-01-21 19:48:09 +080010670
10671 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010672 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010673 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010674 nai.clatd.interfaceLinkStateChanged(iface, up);
10675 }
10676 }
10677
10678 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010679 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010680 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010681 nai.clatd.interfaceRemoved(iface);
10682 }
lucaslin66f44212021-02-23 01:12:55 +080010683 }
10684 }
10685
lucaslin1a8b4c62021-01-21 02:02:55 +080010686 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10687
10688 /**
10689 * Class used for updating network activity tracking with netd and notify network activity
10690 * changes.
10691 */
10692 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010693 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010694 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010695 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010696 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10697 new RemoteCallbackList<>();
10698 // Indicate the current system default network activity is active or not.
10699 @GuardedBy("mActiveIdleTimers")
10700 private boolean mNetworkActive;
10701 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010702 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010703 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010704
Chalard Jean46bfbf02022-02-02 00:56:25 +090010705 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010706 public final int timeout;
10707 public final int transportType;
10708
10709 IdleTimerParams(int timeout, int transport) {
10710 this.timeout = timeout;
10711 this.transportType = transport;
10712 }
10713 }
10714
10715 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010716 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010717 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010718 mNetd = netd;
10719 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010720 }
10721
lucaslin66f44212021-02-23 01:12:55 +080010722 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10723 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10724 synchronized (mActiveIdleTimers) {
10725 mNetworkActive = active;
10726 // If there are no idle timers, it means that system is not monitoring
10727 // activity, so the system default network for those default network
10728 // unspecified apps is always considered active.
10729 //
10730 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10731 // any network activity change event. Whenever this event is received,
10732 // the mActiveIdleTimers should be always not empty. The legacy behavior
10733 // is no-op. Remove to refer to mNetworkActive only.
10734 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10735 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10736 }
10737 }
10738 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010739
lucaslin1193a5d2021-01-21 02:04:15 +080010740 // The network activity should only be updated from ConnectivityService handler thread
10741 // when mActiveIdleTimers lock is held.
10742 @GuardedBy("mActiveIdleTimers")
10743 private void reportNetworkActive() {
10744 final int length = mNetworkActivityListeners.beginBroadcast();
10745 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10746 try {
10747 for (int i = 0; i < length; i++) {
10748 try {
10749 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10750 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010751 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010752 }
10753 }
10754 } finally {
10755 mNetworkActivityListeners.finishBroadcast();
10756 }
10757 }
10758
10759 @GuardedBy("mActiveIdleTimers")
10760 public void handleReportNetworkActivity() {
10761 synchronized (mActiveIdleTimers) {
10762 reportNetworkActive();
10763 }
10764 }
10765
lucaslin1a8b4c62021-01-21 02:02:55 +080010766 // This is deprecated and only to support legacy use cases.
10767 private int transportTypeToLegacyType(int type) {
10768 switch (type) {
10769 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010770 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010771 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010772 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010773 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010774 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010775 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010776 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010777 default:
10778 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10779 }
10780 return ConnectivityManager.TYPE_NONE;
10781 }
10782
10783 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10784 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10785 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10786 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10787 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10788 final long ident = Binder.clearCallingIdentity();
10789 try {
10790 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10791 RECEIVE_DATA_ACTIVITY_CHANGE,
10792 null /* resultReceiver */,
10793 null /* scheduler */,
10794 0 /* initialCode */,
10795 null /* initialData */,
10796 null /* initialExtra */);
10797 } finally {
10798 Binder.restoreCallingIdentity(ident);
10799 }
10800 }
10801
10802 /**
10803 * Setup data activity tracking for the given network.
10804 *
10805 * Every {@code setupDataActivityTracking} should be paired with a
10806 * {@link #removeDataActivityTracking} for cleanup.
10807 */
10808 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10809 final String iface = networkAgent.linkProperties.getInterfaceName();
10810
10811 final int timeout;
10812 final int type;
10813
10814 if (networkAgent.networkCapabilities.hasTransport(
10815 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10816 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010817 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010818 10);
10819 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10820 } else if (networkAgent.networkCapabilities.hasTransport(
10821 NetworkCapabilities.TRANSPORT_WIFI)) {
10822 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010823 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010824 15);
10825 type = NetworkCapabilities.TRANSPORT_WIFI;
10826 } else {
10827 return; // do not track any other networks
10828 }
10829
lucaslinb961efc2021-01-21 02:03:17 +080010830 updateRadioPowerState(true /* isActive */, type);
10831
lucaslin1a8b4c62021-01-21 02:02:55 +080010832 if (timeout > 0 && iface != null) {
10833 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010834 synchronized (mActiveIdleTimers) {
10835 // Networks start up.
10836 mNetworkActive = true;
10837 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10838 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10839 reportNetworkActive();
10840 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010841 } catch (Exception e) {
10842 // You shall not crash!
10843 loge("Exception in setupDataActivityTracking " + e);
10844 }
10845 }
10846 }
10847
10848 /**
10849 * Remove data activity tracking when network disconnects.
10850 */
10851 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10852 final String iface = networkAgent.linkProperties.getInterfaceName();
10853 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10854
lucaslinb961efc2021-01-21 02:03:17 +080010855 if (iface == null) return;
10856
10857 final int type;
10858 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10859 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10860 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10861 type = NetworkCapabilities.TRANSPORT_WIFI;
10862 } else {
10863 return; // do not track any other networks
10864 }
10865
10866 try {
10867 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010868 synchronized (mActiveIdleTimers) {
10869 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10870 // The call fails silently if no idle timer setup for this interface
10871 mNetd.idletimerRemoveInterface(iface, params.timeout,
10872 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010873 }
lucaslinb961efc2021-01-21 02:03:17 +080010874 } catch (Exception e) {
10875 // You shall not crash!
10876 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010877 }
10878 }
10879
10880 /**
10881 * Update data activity tracking when network state is updated.
10882 */
10883 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10884 NetworkAgentInfo oldNetwork) {
10885 if (newNetwork != null) {
10886 setupDataActivityTracking(newNetwork);
10887 }
10888 if (oldNetwork != null) {
10889 removeDataActivityTracking(oldNetwork);
10890 }
10891 }
lucaslinb961efc2021-01-21 02:03:17 +080010892
10893 private void updateRadioPowerState(boolean isActive, int transportType) {
10894 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10895 switch (transportType) {
10896 case NetworkCapabilities.TRANSPORT_CELLULAR:
10897 bs.reportMobileRadioPowerState(isActive, NO_UID);
10898 break;
10899 case NetworkCapabilities.TRANSPORT_WIFI:
10900 bs.reportWifiRadioPowerState(isActive, NO_UID);
10901 break;
10902 default:
10903 logw("Untracked transport type:" + transportType);
10904 }
10905 }
lucaslin1193a5d2021-01-21 02:04:15 +080010906
10907 public boolean isDefaultNetworkActive() {
10908 synchronized (mActiveIdleTimers) {
10909 // If there are no idle timers, it means that system is not monitoring activity,
10910 // so the default network is always considered active.
10911 //
10912 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10913 // tracking is disabled (negative idle timer value configured), or no active default
10914 // network. In the latter case, this reports active but it should report inactive.
10915 return mNetworkActive || mActiveIdleTimers.isEmpty();
10916 }
10917 }
10918
10919 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10920 mNetworkActivityListeners.register(l);
10921 }
10922
10923 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10924 mNetworkActivityListeners.unregister(l);
10925 }
lucaslin012f7a12021-01-21 02:04:35 +080010926
10927 public void dump(IndentingPrintWriter pw) {
10928 synchronized (mActiveIdleTimers) {
10929 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10930 pw.println("Idle timers:");
10931 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10932 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10933 final IdleTimerParams params = ent.getValue();
10934 pw.print(" timeout="); pw.print(params.timeout);
10935 pw.print(" type="); pw.println(params.transportType);
10936 }
10937 }
10938 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010939 }
James Mattis47db0582021-01-01 14:13:35 -080010940
Daniel Brightf9e945b2020-06-15 16:10:01 -070010941 /**
10942 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10943 *
10944 * @param socketInfo the socket information
10945 * @param callback the callback to register
10946 */
10947 @Override
10948 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10949 @NonNull final IQosCallback callback) {
10950 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10951 if (nai == null || nai.networkCapabilities == null) {
10952 try {
10953 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10954 } catch (final RemoteException ex) {
10955 loge("registerQosCallbackInternal: RemoteException", ex);
10956 }
10957 return;
10958 }
10959 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10960 }
10961
10962 /**
10963 * Register a {@link IQosCallback} with base {@link QosFilter}.
10964 *
10965 * @param filter the filter to register
10966 * @param callback the callback to register
10967 * @param nai the agent information related to the filter's network
10968 */
10969 @VisibleForTesting
10970 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10971 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010972 Objects.requireNonNull(filter, "filter must be non-null");
10973 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010974
10975 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010976 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10977 // on this network is unregistered when the app loses permission or b) no QoS
10978 // callbacks are sent for restricted networks unless the app currently has permission
10979 // to access restricted networks.
10980 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010981 }
10982 mQosCallbackTracker.registerCallback(callback, filter, nai);
10983 }
10984
10985 /**
10986 * Unregisters the given callback.
10987 *
10988 * @param callback the callback to unregister
10989 */
10990 @Override
10991 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010992 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010993 mQosCallbackTracker.unregisterCallback(callback);
10994 }
James Mattis47db0582021-01-01 14:13:35 -080010995
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010996 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10997 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10998 // Enterprise device can be fully managed like device owner and such use case
10999 // also should be supported. Calling app check for work profile and fully managed device
11000 // is already done in DevicePolicyManager.
11001 // This check is an extra caution to be sure device is fully managed or not.
11002 final UserManager um = mContext.getSystemService(UserManager.class);
11003 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11004 if (um.isManagedProfile(profile.getIdentifier())) {
11005 return true;
11006 }
11007 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
11008 return false;
11009 }
11010
James Mattis45d81842021-01-10 14:24:24 -080011011 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011012 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011013 *
11014 * See the documentation for the individual preferences for a description of the supported
11015 * behaviors.
11016 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011017 * @param profile If the device owner is set, any profile is allowed.
11018 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011019 * @param preferences the list of profile network preferences for the
11020 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011021 * @param listener an optional listener to listen for completion of the operation.
11022 */
11023 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011024 public void setProfileNetworkPreferences(
11025 @NonNull final UserHandle profile,
11026 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011027 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011028 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011029 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011030
11031 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011032 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11033 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11034 .build();
11035 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011036 }
11037
paulhu3ffffe72021-09-16 10:15:22 +080011038 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011039 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011040 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011041 }
11042 if (profile.getIdentifier() < 0) {
11043 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11044 + "UserHandle.CURRENT not supported)");
11045 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011046 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11047 throw new IllegalArgumentException("Profile must be a managed profile "
11048 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011049 }
paulhuaa0743d2021-05-26 21:56:03 +080011050
Chalard Jean0606fc82022-12-14 20:34:43 +090011051 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011052 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011053 for (final ProfileNetworkPreference preference : preferences) {
11054 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011055 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011056 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011057 switch (preference.getPreference()) {
11058 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11059 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011060 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011061 if (preference.getPreferenceEnterpriseId() != 0) {
11062 throw new IllegalArgumentException(
11063 "Invalid enterprise identifier in setProfileNetworkPreferences");
11064 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011065 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011066 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11067 blockingNonEnterprise = true;
11068 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011069 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11070 allowFallback = false;
11071 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011072 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011073 // This code is needed even though there is a check later on,
11074 // because isRangeAlreadyInPreferenceList assumes that every preference
11075 // has a UID list.
11076 if (hasDefaultPreference) {
11077 throw new IllegalArgumentException(
11078 "Default profile preference should not be set along with other "
11079 + "preference");
11080 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011081 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11082 throw new IllegalArgumentException(
11083 "Invalid enterprise identifier in setProfileNetworkPreferences");
11084 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011085 final Set<UidRange> uidRangeSet =
11086 getUidListToBeAppliedForNetworkPreference(profile, preference);
11087 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11088 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11089 } else {
11090 throw new IllegalArgumentException(
11091 "Overlapping uid range in setProfileNetworkPreferences");
11092 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011093 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011094 nc.addEnterpriseId(
11095 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011096 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11097 break;
11098 default:
11099 throw new IllegalArgumentException(
11100 "Invalid preference in setProfileNetworkPreferences");
11101 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011102 preferenceList.add(new ProfileNetworkPreferenceInfo(
11103 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011104 if (hasDefaultPreference && preferenceList.size() > 1) {
11105 throw new IllegalArgumentException(
11106 "Default profile preference should not be set along with other preference");
11107 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011108 }
11109 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011110 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011111 }
11112
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011113 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11114 @NonNull final UserHandle profile,
11115 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11116 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011117 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11118 profileNetworkPreference.getIncludedUids());
11119
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011120 if (uidRangeSet.size() > 0) {
11121 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11122 throw new IllegalArgumentException(
11123 "Allow uid range is outside the uid range of profile.");
11124 }
11125 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011126 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011127 profileNetworkPreference.getExcludedUids());
11128 if (disallowUidRangeSet.size() > 0) {
11129 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11130 throw new IllegalArgumentException(
11131 "disallow uid range is outside the uid range of profile.");
11132 }
11133 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11134 disallowUidRangeSet);
11135 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011136 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011137 uidRangeSet.add(profileUids);
11138 }
11139 }
11140 return uidRangeSet;
11141 }
11142
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011143 private boolean isEnterpriseIdentifierValid(
11144 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011145 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011146 return true;
11147 }
11148 return false;
11149 }
11150
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011151 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011152 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011153 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011154 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011155 // The NRI for a user should contain the request for capabilities.
11156 // If fallback to default network is needed then NRI should include
11157 // the request for the default network. Create an image of it to
11158 // have the correct UIDs in it (also a request can only be part of one NRI, because
11159 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011160 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11161 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011162 if (pref.allowFallback) {
11163 nrs.add(createDefaultInternetRequestForTransport(
11164 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11165 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011166 if (VDBG) {
11167 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11168 pref.capabilities.getUids()));
11169 }
11170
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011171 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011172 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011173 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011174 result.add(nri);
11175 }
11176 return result;
11177 }
11178
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011179 /**
11180 * Compare if the given UID range sets have the same UIDs.
11181 *
11182 */
11183 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011184 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011185 @NonNull Set<UidRange> uidRangeSet) {
11186 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11187 return false;
11188 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011189 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011190 if (UidRangeUtils.doesRangeSetOverlap(
11191 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11192 return true;
11193 }
11194 }
11195 return false;
11196 }
11197
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011198 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011199 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011200 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011201 /*
11202 * handleSetProfileNetworkPreference is always called for single user.
11203 * preferenceList only contains preferences for different uids within the same user
11204 * (enforced by getUidListToBeAppliedForNetworkPreference).
11205 * Clear all the existing preferences for the user before applying new preferences.
11206 *
11207 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011208 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11209 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011210 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11211 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011212
paulhu74128522021-09-28 02:29:03 +000011213 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11214 addPerAppDefaultNetworkRequests(
11215 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011216 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011217
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011218 // Finally, rematch.
11219 rematchAllNetworksAndRequests();
11220
11221 if (null != listener) {
11222 try {
11223 listener.onComplete();
11224 } catch (RemoteException e) {
11225 loge("Listener for setProfileNetworkPreference has died");
11226 }
11227 }
11228 }
11229
paulhu51f77dc2021-06-07 02:34:20 +000011230 @VisibleForTesting
11231 @NonNull
11232 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11233 @NonNull final Set<Integer> uids) {
11234 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11235 if (uids.size() == 0) {
11236 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11237 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11238 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11239 return nris;
11240 }
11241
11242 final List<NetworkRequest> requests = new ArrayList<>();
11243 // The NRI should be comprised of two layers:
11244 // - The request for the mobile network preferred.
11245 // - The request for the default network, for fallback.
11246 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011247 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011248 requests.add(createDefaultInternetRequestForTransport(
11249 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11250 final Set<UidRange> ranges = new ArraySet<>();
11251 for (final int uid : uids) {
11252 ranges.add(new UidRange(uid, uid));
11253 }
11254 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011255 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011256 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011257 return nris;
11258 }
11259
11260 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011261 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011262 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11263 addPerAppDefaultNetworkRequests(
11264 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011265 // Finally, rematch.
11266 rematchAllNetworksAndRequests();
11267 }
11268
Patrick Rohr2857ac42022-01-21 14:58:16 +010011269 private void handleIngressRateLimitChanged() {
11270 final long oldIngressRateLimit = mIngressRateLimit;
11271 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11272 mContext);
11273 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11274 if (canNetworkBeRateLimited(networkAgent)) {
11275 // If rate limit has previously been enabled, remove the old limit first.
11276 if (oldIngressRateLimit >= 0) {
11277 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11278 }
11279 if (mIngressRateLimit >= 0) {
11280 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11281 mIngressRateLimit);
11282 }
11283 }
11284 }
11285 }
11286
11287 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011288 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
11289 if (!SdkLevel.isAtLeastT()) return false;
11290
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011291 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11292 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11293 // internet connectivity can be rate limited.
11294 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11295 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011296 return false;
11297 }
11298
11299 final String iface = networkAgent.linkProperties.getInterfaceName();
11300 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011301 // This may happen in tests, but if there is no interface then there is nothing that
11302 // can be rate limited.
11303 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011304 return false;
11305 }
11306 return true;
11307 }
11308
James Mattis45d81842021-01-10 14:24:24 -080011309 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011310 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11311 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011312 }
11313
11314 /**
11315 * Used by automotive devices to set the network preferences used to direct traffic at an
11316 * application level as per the given OemNetworkPreferences. An example use-case would be an
11317 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11318 * vehicle via a particular network.
11319 *
11320 * Calling this will overwrite the existing preference.
11321 *
James Mattisda32cfe2021-01-26 16:23:52 -080011322 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011323 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011324 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011325 */
James Mattis47db0582021-01-01 14:13:35 -080011326 @Override
James Mattis45d81842021-01-10 14:24:24 -080011327 public void setOemNetworkPreference(
11328 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011329 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011330
James Mattisfa270db2021-05-31 17:11:10 -070011331 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11332 // Only bypass the permission/device checks if this is a valid test request.
11333 if (isValidTestOemNetworkPreference(preference)) {
11334 enforceManageTestNetworksPermission();
11335 } else {
11336 enforceAutomotiveDevice();
11337 enforceOemNetworkPreferencesPermission();
11338 validateOemNetworkPreferences(preference);
11339 }
James Mattis45d81842021-01-10 14:24:24 -080011340
James Mattis45d81842021-01-10 14:24:24 -080011341 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11342 new Pair<>(preference, listener)));
11343 }
11344
James Mattisfa270db2021-05-31 17:11:10 -070011345 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011346 * Sets the specified UIDs to get/receive the VPN as the only default network.
11347 *
11348 * Calling this will overwrite the existing network preference for this session, and the
11349 * specified UIDs won't get any default network when no VPN is connected.
11350 *
11351 * @param session The VPN session which manages the passed UIDs.
11352 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11353 * setting for this session if the array is empty. Null is not allowed, the
11354 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11355 * @hide
11356 */
11357 @Override
11358 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11359 Objects.requireNonNull(ranges);
11360 enforceNetworkStackOrSettingsPermission();
11361 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11362 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11363 throw new IllegalArgumentException(
11364 "setVpnNetworkPreference: Passed UID ranges overlap");
11365 }
11366
11367 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11368 new VpnNetworkPreferenceInfo(session,
11369 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11370 }
11371
11372 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11373 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11374
11375 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11376 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11377
11378 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11379 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11380 // Finally, rematch.
11381 rematchAllNetworksAndRequests();
11382 }
11383
11384 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11385 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11386 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11387 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11388 final List<NetworkRequest> requests = new ArrayList<>();
11389 // Request VPN only, so other networks won't be the fallback options when VPN is not
11390 // connected temporarily.
11391 requests.add(createVpnRequest());
11392 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11393 setNetworkRequestUids(requests, uidRanges);
11394 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11395 }
11396 return nris;
11397 }
11398
11399 /**
James Mattisfa270db2021-05-31 17:11:10 -070011400 * Check the validity of an OEM network preference to be used for testing purposes.
11401 * @param preference the preference to validate
11402 * @return true if this is a valid OEM network preference test request.
11403 */
11404 private boolean isValidTestOemNetworkPreference(
11405 @NonNull final OemNetworkPreferences preference) {
11406 // Allow for clearing of an existing OemNetworkPreference used for testing.
11407 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11408 // changes after this check is complete. This is an unlikely scenario as calling of this API
11409 // is controlled by the OEM therefore the added complexity is not worth adding given those
11410 // circumstances. That said, it is an edge case to be aware of hence this comment.
11411 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11412 && isTestOemNetworkPreference(mOemNetworkPreferences);
11413 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11414 }
11415
11416 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11417 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11418 return prefMap.size() == 1
11419 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11420 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11421 }
11422
James Mattis45d81842021-01-10 14:24:24 -080011423 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11424 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11425 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011426 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11427 throw new IllegalArgumentException(
11428 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11429 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011430 }
11431 }
11432 }
11433
11434 private void handleSetOemNetworkPreference(
11435 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011436 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011437 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11438 if (DBG) {
11439 log("set OEM network preferences :" + preference.toString());
11440 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011441
James Mattiscb1e0362021-04-06 17:07:42 -070011442 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011443 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11444 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11445 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011446 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011447
11448 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011449 try {
11450 listener.onComplete();
11451 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011452 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011453 }
James Mattis45d81842021-01-10 14:24:24 -080011454 }
11455 }
11456
paulhu74128522021-09-28 02:29:03 +000011457 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011458 // Skip the requests which are set by other network preference. Because the uid range rules
11459 // should stay in netd.
11460 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011461 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011462 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011463 }
11464
James Mattis3ce3d3c2021-02-09 18:18:28 -080011465 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11466 ensureRunningOnConnectivityServiceThread();
11467 mDefaultNetworkRequests.addAll(nris);
11468 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11469 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011470 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011471 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11472 nrisToRegister.addAll(
11473 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11474 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011475 }
11476
11477 /**
11478 * All current requests that are tracking the default network need to be assessed as to whether
11479 * or not the current set of per-application default requests will be changing their default
11480 * network. If so, those requests will need to be updated so that they will send callbacks for
11481 * default network changes at the appropriate time. Additionally, those requests tracking the
11482 * default that were previously updated by this flow will need to be reassessed.
11483 * @return the nris which will need to be updated.
11484 */
11485 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11486 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11487 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11488 // same nri in the map's values for each of its NetworkRequest objects.
11489 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011490 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011491 // Include this nri if it is currently being tracked.
11492 if (isPerAppTrackedNri(nri)) {
11493 defaultCallbackRequests.add(nri);
11494 continue;
11495 }
11496 // We only track callbacks for requests tracking the default.
11497 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11498 continue;
11499 }
11500 // Include this nri if it will be tracked by the new per-app default requests.
11501 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011502 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011503 if (isNriGoingToBeTracked) {
11504 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011505 }
11506 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011507 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011508 }
11509
James Mattis3ce3d3c2021-02-09 18:18:28 -080011510 /**
11511 * Create nris for those network requests that are currently tracking the default network that
11512 * are being controlled by a per-application default.
11513 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11514 * foundation when creating the nri. Important items include the calling uid's original
11515 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11516 * requests are assumed to have already been validated as needing to be updated.
11517 * @return the Set of nris to use when registering network requests.
11518 */
11519 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11520 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11521 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11522 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11523 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011524 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011525
Chalard Jean9473c982021-07-29 20:03:04 +090011526 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011527 if (trackingNri == mDefaultRequest) {
11528 callbackRequestsToRegister.add(new NetworkRequestInfo(
11529 callbackRequest,
11530 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11531 continue;
11532 }
11533
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011534 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011535 callbackRequestsToRegister.add(new NetworkRequestInfo(
11536 callbackRequest,
11537 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011538 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011539 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011540 }
11541 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011542 }
11543
Chalard Jean17215832021-03-01 14:06:28 +090011544 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11545 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011546 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011547 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011548 }
11549 }
11550
James Mattis45d81842021-01-10 14:24:24 -080011551 /**
11552 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11553 */
11554 @VisibleForTesting
11555 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011556 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011557 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011558 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011559 final SparseArray<Set<Integer>> uids =
11560 createUidsFromOemNetworkPreferences(preference);
11561 for (int i = 0; i < uids.size(); i++) {
11562 final int key = uids.keyAt(i);
11563 final Set<Integer> value = uids.valueAt(i);
11564 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11565 // No need to add an nri without any requests.
11566 if (0 == nri.mRequests.size()) {
11567 continue;
11568 }
11569 nris.add(nri);
11570 }
11571
11572 return nris;
11573 }
11574
11575 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11576 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011577 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011578 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011579 final List<UserHandle> users =
11580 mContext.getSystemService(UserManager.class).getUserHandles(true);
11581 if (null == users || users.size() == 0) {
11582 if (VDBG || DDBG) {
11583 log("No users currently available for setting the OEM network preference.");
11584 }
James Mattisb6b6a432021-06-01 22:30:36 -070011585 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011586 }
James Mattis45d81842021-01-10 14:24:24 -080011587 for (final Map.Entry<String, Integer> entry :
11588 preference.getNetworkPreferences().entrySet()) {
11589 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011590 // Add the rules for all users as this policy is device wide.
11591 for (final UserHandle user : users) {
11592 try {
11593 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11594 if (!prefToUids.contains(pref)) {
11595 prefToUids.put(pref, new ArraySet<>());
11596 }
11597 prefToUids.get(pref).add(uid);
11598 } catch (PackageManager.NameNotFoundException e) {
11599 // Although this may seem like an error scenario, it is ok that uninstalled
11600 // packages are sent on a network preference as the system will watch for
11601 // package installations associated with this network preference and update
11602 // accordingly. This is done to minimize race conditions on app install.
11603 continue;
James Mattis45d81842021-01-10 14:24:24 -080011604 }
James Mattis45d81842021-01-10 14:24:24 -080011605 }
11606 }
James Mattisb6b6a432021-06-01 22:30:36 -070011607 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011608 }
11609
11610 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11611 @OemNetworkPreferences.OemNetworkPreference final int preference,
11612 @NonNull final Set<Integer> uids) {
11613 final List<NetworkRequest> requests = new ArrayList<>();
11614 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11615 switch (preference) {
11616 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11617 requests.add(createUnmeteredNetworkRequest());
11618 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011619 requests.add(createDefaultInternetRequestForTransport(
11620 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011621 break;
11622 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11623 requests.add(createUnmeteredNetworkRequest());
11624 requests.add(createOemPaidNetworkRequest());
11625 break;
11626 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11627 requests.add(createOemPaidNetworkRequest());
11628 break;
11629 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11630 requests.add(createOemPrivateNetworkRequest());
11631 break;
James Mattisfa270db2021-05-31 17:11:10 -070011632 case OEM_NETWORK_PREFERENCE_TEST:
11633 requests.add(createUnmeteredNetworkRequest());
11634 requests.add(createTestNetworkRequest());
11635 requests.add(createDefaultRequest());
11636 break;
11637 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11638 requests.add(createTestNetworkRequest());
11639 break;
James Mattis45d81842021-01-10 14:24:24 -080011640 default:
11641 // This should never happen.
11642 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11643 + " called with invalid preference of " + preference);
11644 }
11645
James Mattisfa270db2021-05-31 17:11:10 -070011646 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011647 for (final int uid : uids) {
11648 ranges.add(new UidRange(uid, uid));
11649 }
11650 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011651 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011652 }
11653
11654 private NetworkRequest createUnmeteredNetworkRequest() {
11655 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11656 .addCapability(NET_CAPABILITY_NOT_METERED)
11657 .addCapability(NET_CAPABILITY_VALIDATED);
11658 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11659 }
11660
11661 private NetworkRequest createOemPaidNetworkRequest() {
11662 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11663 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11664 .addCapability(NET_CAPABILITY_OEM_PAID)
11665 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11666 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11667 }
11668
11669 private NetworkRequest createOemPrivateNetworkRequest() {
11670 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11671 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11672 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11673 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11674 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11675 }
11676
11677 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011678 final NetworkCapabilities netcap = new NetworkCapabilities();
11679 netcap.addCapability(NET_CAPABILITY_INTERNET);
11680 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11681 return netcap;
11682 }
11683
11684 private NetworkRequest createTestNetworkRequest() {
11685 final NetworkCapabilities netcap = new NetworkCapabilities();
11686 netcap.clearAll();
11687 netcap.addTransportType(TRANSPORT_TEST);
11688 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011689 }
James Mattis47db0582021-01-01 14:13:35 -080011690 }
markchien738ad912021-12-09 18:15:45 +080011691
11692 @Override
11693 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11694 enforceNetworkStackOrSettingsPermission();
11695
11696 try {
11697 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011698 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011699 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011700 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011701 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011702 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011703 throw new IllegalStateException(e);
11704 }
11705 }
11706
11707 @Override
11708 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11709 enforceNetworkStackOrSettingsPermission();
11710
11711 try {
11712 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011713 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011714 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011715 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011716 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011717 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011718 throw new IllegalStateException(e);
11719 }
11720 }
markchiene1561fa2021-12-09 22:00:56 +080011721
11722 @Override
markchien3c04e662022-03-22 16:29:56 +080011723 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011724 enforceNetworkStackOrSettingsPermission();
11725
markchien3c04e662022-03-22 16:29:56 +080011726 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11727 int firewallRule = getFirewallRuleType(chain, rule);
11728
11729 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11730 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11731 }
11732
markchiene1561fa2021-12-09 22:00:56 +080011733 try {
markchien3c04e662022-03-22 16:29:56 +080011734 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011735 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011736 throw new IllegalStateException(e);
11737 }
11738 }
markchien98a6f952022-01-13 23:43:53 +080011739
markchien3c04e662022-03-22 16:29:56 +080011740 private int getFirewallRuleType(int chain, int rule) {
11741 final int defaultRule;
11742 switch (chain) {
11743 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011744 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11745 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011746 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011747 defaultRule = FIREWALL_RULE_ALLOW;
11748 break;
11749 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11750 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11751 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11752 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11753 defaultRule = FIREWALL_RULE_DENY;
11754 break;
11755 default:
11756 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11757 }
11758 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11759
11760 return rule;
11761 }
11762
markchien98a6f952022-01-13 23:43:53 +080011763 @Override
11764 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11765 enforceNetworkStackOrSettingsPermission();
11766
11767 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011768 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011769 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011770 throw new IllegalStateException(e);
11771 }
11772 }
11773
markchien00a0bed2022-01-13 23:46:13 +080011774 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011775 public boolean getFirewallChainEnabled(final int chain) {
11776 enforceNetworkStackOrSettingsPermission();
11777
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011778 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011779 }
11780
11781 @Override
markchien00a0bed2022-01-13 23:46:13 +080011782 public void replaceFirewallChain(final int chain, final int[] uids) {
11783 enforceNetworkStackOrSettingsPermission();
11784
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011785 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011786 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080011787
11788 @Override
11789 public IBinder getCompanionDeviceManagerProxyService() {
11790 enforceNetworkStackPermission(mContext);
11791 return mCdmps;
11792 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011793}