blob: a570ab154e84411dd7dd89a7d5e1bef42157efc2 [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 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900769 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
770 * should be shown.
771 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900772 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900773
774 /**
775 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
776 * should be hidden.
777 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900778 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900779
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800780 /**
781 * The maximum alive time to allow bad wifi configuration for testing.
782 */
783 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
784
Patrick Rohr2857ac42022-01-21 14:58:16 +0100785 /**
786 * The priority of the tc police rate limiter -- smaller value is higher priority.
787 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
788 */
789 private static final short TC_PRIO_POLICE = 1;
790
791 /**
792 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
793 */
794 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700795 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100796
Hugo Benichi47011212017-03-30 10:46:05 +0900797 private static String eventName(int what) {
798 return sMagicDecoderRing.get(what, Integer.toString(what));
799 }
800
paulhua10d8212020-11-10 15:32:56 +0800801 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900802 final DnsResolverServiceManager dsm = context.getSystemService(
803 DnsResolverServiceManager.class);
804 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800805 }
806
Cody Kesting73708bf2019-12-18 10:57:50 -0800807 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900808 @VisibleForTesting
809 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700810 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700811 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700812 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700813 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800814 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
815 @VisibleForTesting
816 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
817
Erik Kline32120082017-12-13 19:40:49 +0900818 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900819 @VisibleForTesting
820 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700821
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400822 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800823 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400824
Chalard Jean46bfbf02022-02-02 00:56:25 +0900825 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800826 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700827
Chalard Jean5d70ba42018-06-07 16:44:04 +0900828 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
829 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000830 @VisibleForTesting
831 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400832
Erik Kline05f2b402015-04-30 12:58:40 +0900833 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700834
Chalard Jean46bfbf02022-02-02 00:56:25 +0900835 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400836
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700837 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900838 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700839
Valentin Iftime9fa35092019-09-24 13:32:13 +0200840 private Set<String> mWolSupportedInterfaces;
841
Roshan Pius08c94fb2020-01-16 12:17:17 -0800842 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800843 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800844 private final AppOpsManager mAppOpsManager;
845
846 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400847
chiachangwang3d60bac2023-01-17 14:38:08 +0000848 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900849 private final QosCallbackTracker mQosCallbackTracker;
850 private final NetworkNotificationManager mNotifier;
851 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900852
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700853 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800854 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700855
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900856 // Sequence number for NetworkProvider IDs.
857 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
858 NetworkProvider.FIRST_PROVIDER_ID);
859
Erik Klineedf878b2015-07-09 18:24:03 +0900860 // NetworkRequest activity String log entries.
861 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
862 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
863
Hugo Benichid159fdd2016-07-11 11:05:12 +0900864 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900865 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900866 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
867
Hugo Benichi47011212017-03-30 10:46:05 +0900868 private static final int MAX_WAKELOCK_LOGS = 20;
869 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900870 private int mTotalWakelockAcquisitions = 0;
871 private int mTotalWakelockReleases = 0;
872 private long mTotalWakelockDurationMs = 0;
873 private long mMaxWakelockDurationMs = 0;
874 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900875
Hugo Benichi208c0102016-07-28 17:53:06 +0900876 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900877
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700878 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900879 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700880
Erik Kline95ecfee2016-10-02 18:02:14 +0900881 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900882 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900883
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900884 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800885 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
886 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800887
Patrick Rohr2857ac42022-01-21 14:58:16 +0100888 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
889 // configured via {@link
890 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
891 // Only the handler thread is allowed to access this field.
892 private long mIngressRateLimit = -1;
893
Robert Greenwalt802c1102014-06-02 15:32:02 -0700894 /**
895 * Implements support for the legacy "one network per network type" model.
896 *
897 * We used to have a static array of NetworkStateTrackers, one for each
898 * network type, but that doesn't work any more now that we can have,
899 * for example, more that one wifi network. This class stores all the
900 * NetworkAgentInfo objects that support a given type, but the legacy
901 * API will only see the first one.
902 *
903 * It serves two main purposes:
904 *
905 * 1. Provide information about "the network for a given type" (since this
906 * API only supports one).
907 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
908 * the first network for a given type changes, or if the default network
909 * changes.
910 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900911 @VisibleForTesting
912 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900913
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900914 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900915 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900916
Robert Greenwalt802c1102014-06-02 15:32:02 -0700917 /**
918 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
919 * Each list holds references to all NetworkAgentInfos that are used to
920 * satisfy requests for that network type.
921 *
922 * This array is built out at startup such that an unsupported network
923 * doesn't get an ArrayList instance, making this a tristate:
924 * unsupported, supported but not active and active.
925 *
926 * The actual lists are populated when we scan the network types that
927 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900928 *
929 * Threading model:
930 * - addSupportedType() is only called in the constructor
931 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
932 * They are therefore not thread-safe with respect to each other.
933 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
934 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900935 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900936 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700937 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900938 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900939 @NonNull
940 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700941
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900942 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
943 // an entry have no timer (equivalent to -1). Lazily loaded.
944 @NonNull
945 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
946
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900947 LegacyTypeTracker(@NonNull ConnectivityService service) {
948 mService = service;
949 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700950 }
951
Chiachang Wang3bc52762021-11-25 14:17:57 +0800952 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
953 // addressed.
954 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900955 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
956 final PackageManager pm = ctx.getPackageManager();
957 if (pm.hasSystemFeature(FEATURE_WIFI)) {
958 addSupportedType(TYPE_WIFI);
959 }
960 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
961 addSupportedType(TYPE_WIFI_P2P);
962 }
963 if (tm.isDataCapable()) {
964 // Telephony does not have granular support for these types: they are either all
965 // supported, or none is supported
966 addSupportedType(TYPE_MOBILE);
967 addSupportedType(TYPE_MOBILE_MMS);
968 addSupportedType(TYPE_MOBILE_SUPL);
969 addSupportedType(TYPE_MOBILE_DUN);
970 addSupportedType(TYPE_MOBILE_HIPRI);
971 addSupportedType(TYPE_MOBILE_FOTA);
972 addSupportedType(TYPE_MOBILE_IMS);
973 addSupportedType(TYPE_MOBILE_CBS);
974 addSupportedType(TYPE_MOBILE_IA);
975 addSupportedType(TYPE_MOBILE_EMERGENCY);
976 }
977 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
978 addSupportedType(TYPE_BLUETOOTH);
979 }
980 if (pm.hasSystemFeature(FEATURE_WATCH)) {
981 // TYPE_PROXY is only used on Wear
982 addSupportedType(TYPE_PROXY);
983 }
984 // Ethernet is often not specified in the configs, although many devices can use it via
985 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +0000986 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900987 addSupportedType(TYPE_ETHERNET);
988 }
989
990 // Always add TYPE_VPN as a supported type
991 addSupportedType(TYPE_VPN);
992 }
993
994 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700995 if (mTypeLists[type] != null) {
996 throw new IllegalStateException(
997 "legacy list for type " + type + "already initialized");
998 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900999 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001000 }
1001
Robert Greenwalt802c1102014-06-02 15:32:02 -07001002 public boolean isTypeSupported(int type) {
1003 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1004 }
1005
1006 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001007 synchronized (mTypeLists) {
1008 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1009 return mTypeLists[type].get(0);
1010 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001011 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001012 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001013 }
1014
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001015 public int getRestoreTimerForType(int type) {
1016 synchronized (mTypeLists) {
1017 if (mRestoreTimers == null) {
1018 mRestoreTimers = loadRestoreTimers();
1019 }
1020 return mRestoreTimers.getOrDefault(type, -1);
1021 }
1022 }
1023
1024 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1025 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001026 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001027 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1028 for (final String config : configs) {
1029 final String[] splits = TextUtils.split(config, ",");
1030 if (splits.length != 2) {
1031 logwtf("Invalid restore timer token count: " + config);
1032 continue;
1033 }
1034 try {
1035 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1036 } catch (NumberFormatException e) {
1037 logwtf("Invalid restore timer number format: " + config, e);
1038 }
1039 }
1040 return ret;
1041 }
1042
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001043 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001044 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001045 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001046 log("Sending " + state
1047 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001048 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001049 }
1050 }
1051
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001052 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1053 // network type, to preserve previous behaviour.
1054 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1055 if (vpnNai != mService.getLegacyLockdownNai()) return;
1056
1057 if (vpnNai.declaredUnderlyingNetworks == null
1058 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1059 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1060 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1061 return;
1062 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001063 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001064 vpnNai.declaredUnderlyingNetworks[0]);
1065 if (underlyingNai == null) return;
1066
1067 final int type = underlyingNai.networkInfo.getType();
1068 final DetailedState state = DetailedState.CONNECTED;
1069 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1070 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1071 }
1072
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001073 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001074 public void add(int type, NetworkAgentInfo nai) {
1075 if (!isTypeSupported(type)) {
1076 return; // Invalid network type.
1077 }
1078 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1079
1080 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1081 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001082 return;
1083 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001084 synchronized (mTypeLists) {
1085 list.add(nai);
1086 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001087
Chalard Jean5b409c72021-02-04 13:12:59 +09001088 // Send a broadcast if this is the first network of its type or if it's the default.
1089 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001090
1091 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1092 // to preserve previous behaviour.
1093 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001094 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001095 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1096 mService.sendLegacyNetworkBroadcast(nai, state, type);
1097 }
1098
1099 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1100 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001101 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001102 }
1103
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001104 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001105 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001106 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1107 if (list == null || list.isEmpty()) {
1108 return;
1109 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001110 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001111
Hugo Benichi389633f2016-06-21 09:48:07 +09001112 synchronized (mTypeLists) {
1113 if (!list.remove(nai)) {
1114 return;
1115 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001116 }
1117
Lorenzo Colitti49767722015-05-01 00:30:10 +09001118 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001119 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1120 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001121 }
1122
1123 if (!list.isEmpty() && wasFirstNetwork) {
1124 if (DBG) log("Other network available for type " + type +
1125 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001126 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001127 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001128 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001129 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001130 }
1131 }
1132
1133 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001134 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1135 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001136 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001137 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001138 }
1139 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001140
Chalard Jean46bfbf02022-02-02 00:56:25 +09001141 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001142 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001143 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001144 final DetailedState state = nai.networkInfo.getDetailedState();
1145 for (int type = 0; type < mTypeLists.length; type++) {
1146 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001147 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001148 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001149 if (isFirst || contains && isDefault) {
1150 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001151 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001152 }
1153 }
1154 }
1155
Robert Greenwalt94e22142014-07-30 16:31:24 -07001156 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001157 pw.println("mLegacyTypeTracker:");
1158 pw.increaseIndent();
1159 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001160 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001161 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001162 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001163 pw.println();
1164 pw.println("Current state:");
1165 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001166 synchronized (mTypeLists) {
1167 for (int type = 0; type < mTypeLists.length; type++) {
1168 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1169 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001170 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001171 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001172 }
1173 }
1174 pw.decreaseIndent();
1175 pw.decreaseIndent();
1176 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001177 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001178 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001179 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001180
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001181 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001182 /**
1183 * Helper class which parses out priority arguments and dumps sections according to their
1184 * priority. If priority arguments are omitted, function calls the legacy dump command.
1185 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001186 private class LocalPriorityDump {
1187 private static final String PRIORITY_ARG = "--dump-priority";
1188 private static final String PRIORITY_ARG_HIGH = "HIGH";
1189 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1190
1191 LocalPriorityDump() {}
1192
1193 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1194 doDump(fd, pw, new String[] {DIAG_ARG});
1195 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001196 }
1197
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001198 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1199 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001200 }
1201
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001202 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1203 if (args == null) {
1204 dumpNormal(fd, pw, args);
1205 return;
1206 }
1207
1208 String priority = null;
1209 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1210 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1211 argIndex++;
1212 priority = args[argIndex];
1213 }
1214 }
1215
1216 if (PRIORITY_ARG_HIGH.equals(priority)) {
1217 dumpHigh(fd, pw);
1218 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1219 dumpNormal(fd, pw, args);
1220 } else {
1221 // ConnectivityService publishes binder service using publishBinderService() with
1222 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001223 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1224 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001225 // TODO: Integrate into signal dump.
1226 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001227 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001228 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001229 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001230
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001231 /**
1232 * Dependencies of ConnectivityService, for injection in tests.
1233 */
1234 @VisibleForTesting
1235 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001236 public int getCallingUid() {
1237 return Binder.getCallingUid();
1238 }
1239
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001240 /**
1241 * Get system properties to use in ConnectivityService.
1242 */
1243 public MockableSystemProperties getSystemProperties() {
1244 return new MockableSystemProperties();
1245 }
1246
1247 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001248 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1249 */
1250 public ConnectivityResources getResources(@NonNull Context ctx) {
1251 return new ConnectivityResources(ctx);
1252 }
1253
1254 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001255 * Create a HandlerThread to use in ConnectivityService.
1256 */
1257 public HandlerThread makeHandlerThread() {
1258 return new HandlerThread("ConnectivityServiceThread");
1259 }
1260
1261 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001262 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001263 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001264 public NetworkStackClientBase getNetworkStack() {
1265 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001266 }
1267
1268 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001269 * @see ProxyTracker
1270 */
1271 public ProxyTracker makeProxyTracker(@NonNull Context context,
1272 @NonNull Handler connServiceHandler) {
1273 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1274 }
1275
1276 /**
1277 * @see NetIdManager
1278 */
1279 public NetIdManager makeNetIdManager() {
1280 return new NetIdManager();
1281 }
1282
1283 /**
1284 * @see NetworkUtils#queryUserAccess(int, int)
1285 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001286 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1287 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001288 }
1289
1290 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001291 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1292 * requires CAP_NET_ADMIN, which the unit tests do not have.
1293 */
1294 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1295 InetSocketAddress remote) {
1296 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1297 }
1298
1299 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001300 * @see MultinetworkPolicyTracker
1301 */
1302 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1303 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1304 return new MultinetworkPolicyTracker(c, h, r);
1305 }
1306
Aaron Huang330a4c02020-10-27 03:36:19 +08001307 /**
1308 * @see BatteryStatsManager
1309 */
1310 public void reportNetworkInterfaceForTransports(Context context, String iface,
1311 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001312 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001313 context.getSystemService(BatteryStatsManager.class);
1314 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1315 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001316
1317 public boolean getCellular464XlatEnabled() {
1318 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1319 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001320
1321 /**
1322 * @see PendingIntent#intentFilterEquals
1323 */
1324 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1325 return a.intentFilterEquals(b);
1326 }
1327
1328 /**
1329 * @see LocationPermissionChecker
1330 */
1331 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1332 return new LocationPermissionChecker(context);
1333 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001334
1335 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001336 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001337 *
1338 * This method returns null in versions before T, where carrier privilege
1339 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001340 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001341 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001342 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1343 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1344 if (SdkLevel.isAtLeastT()) {
1345 return new CarrierPrivilegeAuthenticator(context, tm);
1346 } else {
1347 return null;
1348 }
1349 }
1350
1351 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001352 * @see DeviceConfigUtils#isFeatureEnabled
1353 */
1354 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1355 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1356 TETHERING_MODULE_NAME, defaultEnabled);
1357 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001358
1359 /**
1360 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001361 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001362 * @return BpfNetMaps implementation.
1363 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001364 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1365 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001366 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001367
1368 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001369 * @see ClatCoordinator
1370 */
1371 public ClatCoordinator getClatCoordinator(INetd netd) {
1372 return new ClatCoordinator(
1373 new ClatCoordinator.Dependencies() {
1374 @NonNull
1375 public INetd getNetd() {
1376 return netd;
1377 }
1378 });
1379 }
1380
1381 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001382 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1383 */
1384 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1385 final InterfaceParams params = InterfaceParams.getByName(iface);
1386 if (params == null) {
1387 // the interface might have disappeared.
1388 logw("Failed to get interface params for interface " + iface);
1389 return;
1390 }
1391 try {
1392 // converting rateInBytesPerSecond from long to int is safe here because the
1393 // setting's range is limited to INT_MAX.
1394 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001395 Log.i(TAG,
1396 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001397 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1398 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1399 } catch (IOException e) {
1400 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1401 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1402 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1403 + ") failure: ", e);
1404 }
1405 }
1406
1407 /**
1408 * Wraps {@link TcUtils#tcFilterDelDev}
1409 */
1410 public void disableIngressRateLimit(String iface) {
1411 final InterfaceParams params = InterfaceParams.getByName(iface);
1412 if (params == null) {
1413 // the interface might have disappeared.
1414 logw("Failed to get interface params for interface " + iface);
1415 return;
1416 }
1417 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001418 Log.i(TAG,
1419 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001420 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1421 } catch (IOException e) {
1422 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1423 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1424 }
1425 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001426
1427 /**
1428 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1429 */
1430 // TODO: when available in all active branches:
1431 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1432 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1433 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1434 return BroadcastOptionsShimImpl.newInstance(options);
1435 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001436 }
1437
junyulaie7c7d2a2021-01-26 15:29:15 +08001438 public ConnectivityService(Context context) {
1439 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001440 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1441 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001442 }
1443
1444 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001445 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1446 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001447 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001448
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001449 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001450 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001451 mSystemProperties = mDeps.getSystemProperties();
1452 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001453 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001454 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001455 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1456 // Pass limit - 1 to maintain backward compatibility.
1457 // TODO: Remove the workaround.
1458 mNetworkRequestCounter =
1459 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1460 mSystemNetworkRequestCounter =
1461 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001462
Hugo Benichi208c0102016-07-28 17:53:06 +09001463 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001464 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1465 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001466 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001467 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001468 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001469 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1470 mDefaultNetworkRequests.add(mDefaultRequest);
1471 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001472
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001473 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001474 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001475
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001476 // The default WiFi request is a background request so that apps using WiFi are
1477 // migrated to a better network (typically ethernet) when one comes up, instead
1478 // of staying on WiFi forever.
1479 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1480 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1481
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001482 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1483 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1484 NetworkRequest.Type.BACKGROUND_REQUEST);
1485
Chalard Jean0702f982021-09-16 21:50:07 +09001486 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1487 // TODO: Consider making the timer customizable.
1488 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1489 mCellularRadioTimesharingCapable =
1490 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1491
Paul Hu51f816b2022-08-11 14:43:47 +00001492 mNetd = netd;
1493 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001494 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001495 mPermissionMonitor =
1496 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001497 mHandlerThread.start();
1498 mHandler = new InternalHandler(mHandlerThread.getLooper());
1499 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001500 mConnectivityDiagnosticsHandler =
1501 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001502
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001503 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001504 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001505
junyulaie7c7d2a2021-01-26 15:29:15 +08001506 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001507 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001508 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001509 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001510
Wink Saville32506bc2013-06-29 21:10:57 -07001511 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001512 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001513 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001514 mCarrierPrivilegeAuthenticator =
1515 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001516
Sudheer Shanka9967d462021-03-18 19:09:25 +00001517 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001518 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1519 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001520 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001521
1522 final PowerManager powerManager = (PowerManager) context.getSystemService(
1523 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001524 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001525 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001526
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001527 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1528 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001529 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001530 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001531 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001532 mProtectedNetworks.add(p);
1533 } else {
1534 if (DBG) loge("Ignoring protectedNetwork " + p);
1535 }
1536 }
1537
soma, kawata29444ae2019-05-23 09:30:40 +09001538 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1539
James Mattis02220e22021-03-13 19:27:21 -08001540 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001541 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001542 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001543 final IntentFilter userIntentFilter = new IntentFilter();
1544 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1545 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1546 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1547 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001548
James Mattis02220e22021-03-13 19:27:21 -08001549 // Listen to package add/removes for netd
1550 final IntentFilter packageIntentFilter = new IntentFilter();
1551 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1552 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1553 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1554 packageIntentFilter.addDataScheme("package");
1555 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001556 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001557
lucaslind5c2d072021-02-20 18:59:47 +08001558 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001559
Chalard Jean46bfbf02022-02-02 00:56:25 +09001560 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001561 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001562 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001563 } catch (RemoteException | ServiceSpecificException e) {
1564 loge("Error registering event listener :" + e);
1565 }
1566
Erik Kline05f2b402015-04-30 12:58:40 +09001567 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1568 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001569
chiachangwang3d60bac2023-01-17 14:38:08 +00001570 mKeepaliveTracker = new AutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001571 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001572 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001573
1574 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001575 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001576 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1577 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001578 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001579 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1580 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001581
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001582 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001583 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001584 mNetworkRanker =
1585 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1586
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001587 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001588
Chiachang Wangc1215d32020-10-20 15:38:58 +08001589 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001590 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001591
Chalard Jean28018572020-12-21 18:36:52 +09001592 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1593 // request that doesn't allow fallback to the default network. It should never be visible
1594 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1595 // arguments like the handler or the DnsResolver.
1596 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001597 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001598 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001599 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001600 new LinkProperties(), new NetworkCapabilities(),
1601 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001602 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1603 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001604
1605 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001606 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1607 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1608 // Even if it could, running on S would at least require mocking out the BPF map,
1609 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1610 // the bpf syscall. http://aosp/1907693
1611 if (SdkLevel.isAtLeastT()) {
1612 mDscpPolicyTracker = new DscpPolicyTracker();
1613 }
Tyler Wear72388212021-09-09 14:49:02 -07001614 } catch (ErrnoException e) {
1615 loge("Unable to create DscpPolicyTracker");
1616 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001617
1618 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1619 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001620
1621 if (SdkLevel.isAtLeastT()) {
1622 mCdmps = new CompanionDeviceManagerProxyService(context);
1623 } else {
1624 mCdmps = null;
1625 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001626 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001627
Xiao Ma0a171c02022-01-23 16:14:51 +00001628 /**
1629 * Check whether or not the device supports Ethernet transport.
1630 */
1631 public static boolean deviceSupportsEthernet(final Context context) {
1632 final PackageManager pm = context.getPackageManager();
1633 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1634 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1635 }
1636
Chalard Jean46adcf32018-04-18 20:18:38 +09001637 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001638 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1639 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001640 }
1641
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001642 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1643 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001644 final NetworkCapabilities netCap = new NetworkCapabilities();
1645 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001646 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001647 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001648 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001649 return netCap;
1650 }
1651
James Mattis45d81842021-01-10 14:24:24 -08001652 private NetworkRequest createDefaultRequest() {
1653 return createDefaultInternetRequestForTransport(
1654 TYPE_NONE, NetworkRequest.Type.REQUEST);
1655 }
1656
lucaslin3ba7cc22022-12-19 02:35:33 +00001657 private NetworkRequest createVpnRequest() {
1658 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1659 .withoutDefaultCapabilities()
1660 .addTransportType(TRANSPORT_VPN)
1661 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1662 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1663 .build();
1664 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1665 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1666 }
1667
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001668 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001669 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001670 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001671 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001672 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001673 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001674 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001675 netCap.addTransportType(transportType);
1676 }
James Mattis45d81842021-01-10 14:24:24 -08001677 return createNetworkRequest(type, netCap);
1678 }
1679
1680 private NetworkRequest createNetworkRequest(
1681 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001682 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001683 }
1684
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001685 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1686 NetworkRequest.Type type) {
1687 final NetworkCapabilities netCap = new NetworkCapabilities();
1688 netCap.clearAll();
1689 netCap.addCapability(capability);
1690 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1691 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1692 }
1693
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001694 // Used only for testing.
1695 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001696 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001697 // changing ContentResolver to make registerContentObserver non-final).
1698 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1699 // by subclassing SettingsObserver.
1700 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001701 void updateAlwaysOnNetworks() {
1702 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001703 }
1704
Erik Kline9a62f012018-03-21 07:18:33 -07001705 // See FakeSettingsProvider comment above.
1706 @VisibleForTesting
1707 void updatePrivateDnsSettings() {
1708 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1709 }
1710
paulhu51f77dc2021-06-07 02:34:20 +00001711 @VisibleForTesting
1712 void updateMobileDataPreferredUids() {
1713 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1714 }
1715
Patrick Rohr2857ac42022-01-21 14:58:16 +01001716 @VisibleForTesting
1717 void updateIngressRateLimit() {
1718 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1719 }
1720
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001721 private void handleAlwaysOnNetworkRequest(
1722 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001723 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001724 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001725 handleAlwaysOnNetworkRequest(networkRequest, enable);
1726 }
1727
1728 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001729 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001730 if (enable == isEnabled) {
1731 return; // Nothing to do.
1732 }
1733
1734 if (enable) {
1735 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001736 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001737 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001738 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001739 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001740 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1741 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001742 }
1743 }
1744
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001745 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001746 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1747 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1748 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1749 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001750 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1751 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001752 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001753 }
1754
paulhu51f77dc2021-06-07 02:34:20 +00001755 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001756 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001757 private void registerSettingsCallbacks() {
1758 // Watch for global HTTP proxy changes.
1759 mSettingsObserver.observe(
1760 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1761 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1762
Chalard Jean46bfbf02022-02-02 00:56:25 +09001763 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001764 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001765 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001766 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1767
Chalard Jean46bfbf02022-02-02 00:56:25 +09001768 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001769 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001770 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001771 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001772
1773 // Watch for mobile data preferred uids changes.
1774 mSettingsObserver.observe(
1775 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1776 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001777
1778 // Watch for ingress rate limit changes.
1779 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001780 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001781 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1782 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001783 }
1784
Erik Kline31b4a9e2018-01-11 21:07:29 +09001785 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001786 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1787 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001788 }
1789 }
1790
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001791 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001792 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1793 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001794 return mNextNetworkRequestId++;
1795 }
1796
junyulai74f9a8b2018-06-13 15:00:37 +08001797 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001798 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001799 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001800 if (network == null) {
1801 return null;
1802 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001803 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001804 }
1805
1806 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001807 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001808 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001809 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001810 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001811
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001812 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001813 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001814 private NetworkAgentInfo getVpnForUid(int uid) {
1815 synchronized (mNetworkForNetId) {
1816 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1817 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001818 if (nai.isVPN() && nai.everConnected()
1819 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001820 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001821 }
1822 }
1823 }
1824 return null;
1825 }
1826
Chalard Jean46bfbf02022-02-02 00:56:25 +09001827 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001828 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001829 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001830 final NetworkAgentInfo nai = getVpnForUid(uid);
1831 if (nai != null) return nai.declaredUnderlyingNetworks;
1832 return null;
1833 }
1834
Lorenzo Colittia7574052021-01-19 01:33:05 +09001835 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001836 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001837
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001838 final Network[] networks = getVpnUnderlyingNetworks(uid);
1839 if (networks != null) {
1840 // getUnderlyingNetworks() returns:
1841 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1842 // empty array => the VPN explicitly said "no default network".
1843 // non-empty array => the VPN specified one or more default networks; we use the
1844 // first one.
1845 if (networks.length > 0) {
1846 nai = getNetworkAgentInfoForNetwork(networks[0]);
1847 } else {
1848 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001849 }
1850 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001851 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001852 }
1853
1854 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001855 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001856 */
paulhu7aeba372020-12-30 00:42:19 +08001857 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1858 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001859 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001860 if (ignoreBlocked) {
1861 return false;
1862 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001863 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001864 final long ident = Binder.clearCallingIdentity();
1865 try {
1866 final boolean metered = nc == null ? true : nc.isMetered();
1867 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1868 } finally {
1869 Binder.restoreCallingIdentity(ident);
1870 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001871 }
1872
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001873 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001874 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1875 return;
1876 }
Hugo Benichi47011212017-03-30 10:46:05 +09001877 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001878 synchronized (mBlockedAppUids) {
1879 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001880 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001881 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001882 blocked = false;
1883 } else {
1884 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001885 }
1886 }
Hugo Benichi47011212017-03-30 10:46:05 +09001887 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1888 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1889 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001890 }
1891
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001892 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001893 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1894 return;
1895 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001896 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001897 final int requestId = nri.getActiveRequest() != null
1898 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001899 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001900 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001901 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001902 }
1903
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001904 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001905 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001906 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001907 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001908 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001909 @NonNull
1910 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1911 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001912 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1913 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1914 // but only exists if an app asks about them or requests them. Ensure the requesting app
1915 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001916 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001917 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1918 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1919 null /* extraInfo */);
1920 }
1921 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001922 return filtered;
1923 }
1924
1925 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1926 boolean ignoreBlocked) {
1927 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1928 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001929 }
1930
1931 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001932 * Return NetworkInfo for the active (i.e., connected) network interface.
1933 * It is assumed that at most one network is active at a time. If more
1934 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001935 * @return the info for the active network, or {@code null} if none is
1936 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001937 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001938 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001939 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001940 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001941 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001942 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001943 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1944 if (nai == null) return null;
1945 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1946 maybeLogBlockedNetworkInfo(networkInfo, uid);
1947 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001948 }
1949
Paul Jensen1f567382015-02-13 14:18:39 -05001950 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001951 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001952 public Network getActiveNetwork() {
1953 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001954 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001955 }
1956
1957 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001958 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001959 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001960 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001961 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001962 }
1963
Chalard Jean46bfbf02022-02-02 00:56:25 +09001964 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001965 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001966 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1967 if (vpnNai != null) {
1968 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1969 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1970 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001971 }
Paul Jensen1f567382015-02-13 14:18:39 -05001972 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001973
James Mattis2516da32021-01-31 17:06:19 -08001974 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001975 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1976 ignoreBlocked)) {
1977 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001978 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001979 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001980 }
1981
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001982 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001983 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001984 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001985 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001986 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1987 if (nai == null) return null;
1988 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001989 }
1990
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001991 /** Returns a NetworkInfo object for a network that doesn't exist. */
1992 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1993 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1994 getNetworkTypeName(networkType), "" /* subtypeName */);
1995 info.setIsAvailable(true);
1996 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1997 // background data is restricted.
1998 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1999 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2000 ? DetailedState.BLOCKED
2001 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002002 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2003 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002004 return info;
2005 }
2006
Lorenzo Colittia7574052021-01-19 01:33:05 +09002007 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002008 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2009 return null;
2010 }
2011 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002012 if (nai == null) {
2013 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002014 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002015 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2016 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002017 }
2018
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002019 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002020 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002021 public NetworkInfo getNetworkInfo(int networkType) {
2022 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002023 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002024 if (getVpnUnderlyingNetworks(uid) != null) {
2025 // A VPN is active, so we may need to return one of its underlying networks. This
2026 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002027 // getNetworkAgentInfoForUid.
2028 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2029 if (nai == null) return null;
2030 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2031 if (networkInfo.getType() == networkType) {
2032 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002033 }
2034 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002035 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002036 }
2037
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002038 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002039 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002040 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002041 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002042 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002043 if (nai == null) return null;
2044 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002045 }
2046
2047 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002048 public NetworkInfo[] getAllNetworkInfo() {
2049 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002050 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002051 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2052 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002053 NetworkInfo info = getNetworkInfo(networkType);
2054 if (info != null) {
2055 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002056 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002057 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002058 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002059 }
2060
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002061 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002062 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002063 public Network getNetworkForType(int networkType) {
2064 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002065 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2066 return null;
2067 }
2068 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2069 if (nai == null) {
2070 return null;
2071 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002072 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002073 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2074 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002075 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002076 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002077 }
2078
2079 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002080 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002081 public Network[] getAllNetworks() {
2082 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002083 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002084 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002085 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002086 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002087 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002088 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002089 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002090 }
2091
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002092 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002093 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002094 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002095 // The basic principle is: if an app's traffic could possibly go over a
2096 // network, without the app doing anything multinetwork-specific,
2097 // (hence, by "default"), then include that network's capabilities in
2098 // the array.
2099 //
2100 // In the normal case, app traffic only goes over the system's default
2101 // network connection, so that's the only network returned.
2102 //
2103 // With a VPN in force, some app traffic may go into the VPN, and thus
2104 // over whatever underlying networks the VPN specifies, while other app
2105 // traffic may go over the system default network (e.g.: a split-tunnel
2106 // VPN, or an app disallowed by the VPN), so the set of networks
2107 // returned includes the VPN's underlying networks and the system
2108 // default.
2109 enforceAccessPermission();
2110
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002111 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002112
James Mattis2516da32021-01-31 17:06:19 -08002113 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2114 if (!nri.isBeingSatisfied()) {
2115 continue;
2116 }
2117 final NetworkAgentInfo nai = nri.getSatisfier();
2118 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2119 if (null != nc
2120 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2121 && !result.containsKey(nai.network)) {
2122 result.put(
2123 nai.network,
2124 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002125 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002126 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2127 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002128 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002129 }
2130
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002131 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002132 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002133 if (null != networks) {
2134 for (final Network network : networks) {
2135 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2136 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002137 result.put(
2138 network,
2139 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002140 nc,
2141 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002142 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002143 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002144 }
2145 }
2146 }
2147
2148 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2149 out = result.values().toArray(out);
2150 return out;
2151 }
2152
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002153 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002154 public boolean isNetworkSupported(int networkType) {
2155 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002156 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002157 }
2158
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002159 /**
2160 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002161 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002162 * @return the ip properties for the active network, or {@code null} if
2163 * none is active
2164 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002165 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002166 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002167 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002168 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002169 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2170 if (nai == null) return null;
2171 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002172 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002173 }
2174
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002175 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002176 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002177 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002178 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002179 final LinkProperties lp = getLinkProperties(nai);
2180 if (lp == null) return null;
2181 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002182 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002183 }
2184
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002185 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002186 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002187 public LinkProperties getLinkProperties(Network network) {
2188 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002189 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2190 if (lp == null) return null;
2191 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002192 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002193 }
2194
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002195 @Nullable
2196 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002197 if (nai == null) {
2198 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002199 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002200 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002201 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002202 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002203 }
2204
lucaslinc582d502022-01-27 09:07:00 +08002205 @Override
2206 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002207 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002208 @NonNull String packageName, @Nullable String callingAttributionTag) {
2209 Objects.requireNonNull(packageName);
2210 Objects.requireNonNull(lp);
2211 enforceNetworkStackOrSettingsPermission();
2212 if (!checkAccessPermission(-1 /* pid */, uid)) {
2213 return null;
2214 }
2215 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2216 }
2217
Qingxi Lib2748102020-01-08 12:51:49 -08002218 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2219 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2220 }
2221
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002222 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002223 if (nai == null) return null;
2224 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002225 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002226 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002227 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002228 }
2229
2230 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002231 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2232 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002233 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002234 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002235 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002236 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002237 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002238 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002239 }
2240
lucaslinc582d502022-01-27 09:07:00 +08002241 @Override
lucaslind2b06132022-03-02 10:56:57 +08002242 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2243 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2244 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002245 Objects.requireNonNull(nc);
2246 Objects.requireNonNull(packageName);
2247 enforceNetworkStackOrSettingsPermission();
2248 if (!checkAccessPermission(-1 /* pid */, uid)) {
2249 return null;
2250 }
2251 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2252 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2253 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2254 callingAttributionTag);
2255 }
2256
lucaslin69e1aa92022-03-22 18:15:09 +08002257 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2258 if (nc.getUnderlyingNetworks() != null
2259 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2260 nc.setUnderlyingNetworks(null);
2261 }
2262 }
2263
Qingxi Libb8da982020-01-17 17:54:27 -08002264 @VisibleForTesting
2265 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002266 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002267 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2268 // this would be expensive (one more permission check every time any NC callback is
2269 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2270 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2271 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002272 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002273 if (!checkSettingsPermission(callerPid, callerUid)) {
2274 newNc.setUids(null);
2275 newNc.setSSID(null);
2276 }
Etan Cohen107ae952018-12-30 17:59:59 -08002277 if (newNc.getNetworkSpecifier() != null) {
2278 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2279 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002280 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2281 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2282 newNc.setAdministratorUids(new int[0]);
2283 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002284 if (!checkAnyPermissionOf(
2285 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002286 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002287 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002288 }
lucaslin69e1aa92022-03-22 18:15:09 +08002289 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002290
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002291 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002292 }
2293
Roshan Pius98f59ec2021-02-23 08:47:39 -08002294 /**
2295 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002296 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002297 * NetworkCapabilities.
2298 * Note: This wrapper does not support any sort of invalidation and thus must not be
2299 * persistent or long-lived. It may only be used for the time necessary to
2300 * compute the redactions required by one particular NetworkCallback or
2301 * synchronous call.
2302 */
2303 private class RedactionPermissionChecker {
2304 private final int mCallingPid;
2305 private final int mCallingUid;
2306 @NonNull private final String mCallingPackageName;
2307 @Nullable private final String mCallingAttributionTag;
2308
2309 private Boolean mHasLocationPermission = null;
2310 private Boolean mHasLocalMacAddressPermission = null;
2311 private Boolean mHasSettingsPermission = null;
2312
2313 RedactionPermissionChecker(int callingPid, int callingUid,
2314 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2315 mCallingPid = callingPid;
2316 mCallingUid = callingUid;
2317 mCallingPackageName = callingPackageName;
2318 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002319 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002320
2321 private boolean hasLocationPermissionInternal() {
2322 final long token = Binder.clearCallingIdentity();
2323 try {
2324 return mLocationPermissionChecker.checkLocationPermission(
2325 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2326 null /* message */);
2327 } finally {
2328 Binder.restoreCallingIdentity(token);
2329 }
2330 }
2331
2332 /**
2333 * Returns whether the app holds location permission or not (might return cached result
2334 * if the permission was already checked before).
2335 */
2336 public boolean hasLocationPermission() {
2337 if (mHasLocationPermission == null) {
2338 // If there is no cached result, perform the check now.
2339 mHasLocationPermission = hasLocationPermissionInternal();
2340 }
2341 return mHasLocationPermission;
2342 }
2343
2344 /**
2345 * Returns whether the app holds local mac address permission or not (might return cached
2346 * result if the permission was already checked before).
2347 */
2348 public boolean hasLocalMacAddressPermission() {
2349 if (mHasLocalMacAddressPermission == null) {
2350 // If there is no cached result, perform the check now.
2351 mHasLocalMacAddressPermission =
2352 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2353 }
2354 return mHasLocalMacAddressPermission;
2355 }
2356
2357 /**
2358 * Returns whether the app holds settings permission or not (might return cached
2359 * result if the permission was already checked before).
2360 */
2361 public boolean hasSettingsPermission() {
2362 if (mHasSettingsPermission == null) {
2363 // If there is no cached result, perform the check now.
2364 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2365 }
2366 return mHasSettingsPermission;
2367 }
2368 }
2369
2370 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2371 @NetworkCapabilities.NetCapability long redaction) {
2372 return (redactions & redaction) != 0;
2373 }
2374
2375 /**
2376 * Use the provided |applicableRedactions| to check the receiving app's
2377 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2378 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2379 * before being sent to the corresponding app.
2380 */
2381 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2382 @NetworkCapabilities.RedactionType long applicableRedactions,
2383 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2384 boolean includeLocationSensitiveInfo) {
2385 long redactions = applicableRedactions;
2386 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2387 if (includeLocationSensitiveInfo
2388 && redactionPermissionChecker.hasLocationPermission()) {
2389 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2390 }
2391 }
2392 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2393 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2394 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2395 }
2396 }
2397 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2398 if (redactionPermissionChecker.hasSettingsPermission()) {
2399 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2400 }
2401 }
2402 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002403 }
2404
Qingxi Lib2748102020-01-08 12:51:49 -08002405 @VisibleForTesting
2406 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002407 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002408 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002409 int callingPid, int callingUid, @NonNull String callingPkgName,
2410 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002411 if (nc == null) {
2412 return null;
2413 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002414 // Avoid doing location permission check if the transport info has no location sensitive
2415 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002416 final RedactionPermissionChecker redactionPermissionChecker =
2417 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2418 callingAttributionTag);
2419 final long redactions = retrieveRequiredRedactions(
2420 nc.getApplicableRedactions(), redactionPermissionChecker,
2421 includeLocationSensitiveInfo);
2422 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002423 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002424 // TODO : calling UID is redacted because apps should generally not know what UID is
2425 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002426 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002427 newNc.setOwnerUid(INVALID_UID);
2428 return newNc;
2429 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002430 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2431 if (nc.hasTransport(TRANSPORT_VPN)) {
2432 // Owner UIDs already checked above. No need to re-check.
2433 return newNc;
2434 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002435 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2436 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002437 // compatibility for older apps.
2438 if (!includeLocationSensitiveInfo
2439 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002440 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002441 newNc.setOwnerUid(INVALID_UID);
2442 return newNc;
2443 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002444 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002445 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002446 newNc.setOwnerUid(INVALID_UID);
2447 }
Qingxi Lib2748102020-01-08 12:51:49 -08002448 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002449 }
2450
lucaslinc582d502022-01-27 09:07:00 +08002451 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002452 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2453 LinkProperties lp, int callerPid, int callerUid) {
2454 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002455 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2456 // this would be expensive (one more permission check every time any LP callback is
2457 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2458 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2459 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002460
2461 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2462 final boolean needsSanitization =
2463 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2464 if (!needsSanitization) {
2465 return new LinkProperties(lp);
2466 }
2467
2468 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002469 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002470 }
2471
2472 final LinkProperties newLp = new LinkProperties(lp);
2473 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2474 // object gets parceled.
2475 newLp.setCaptivePortalApiUrl(null);
2476 newLp.setCaptivePortalData(null);
2477 return newLp;
2478 }
2479
Roshan Pius08c94fb2020-01-16 12:17:17 -08002480 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2481 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002482 // There is no need to track the effective UID of the request here. If the caller
2483 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002484 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002485 // Unprivileged apps can only pass in null or their own UID.
2486 if (nc.getUids() == null) {
2487 // If the caller passes in null, the callback will also match networks that do not
2488 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2489 // In this case, redact everything in the request immediately. This ensures that the
2490 // app is not able to get any redacted information by filing an unredacted request
2491 // and observing whether the request matches something.
2492 if (nc.getNetworkSpecifier() != null) {
2493 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2494 }
2495 } else {
2496 nc.setSingleUid(callerUid);
2497 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002498 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002499 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002500 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002501
2502 // Clear owner UID; this can never come from an app.
2503 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002504 }
2505
Chalard Jean38354d12018-03-20 19:13:57 +09002506 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002507 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002508 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2509 }
2510 }
2511
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002512 @Override
2513 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2514 enforceAccessPermission();
2515 final int callerUid = Binder.getCallingUid();
2516 final long token = Binder.clearCallingIdentity();
2517 try {
2518 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2519 } finally {
2520 Binder.restoreCallingIdentity(token);
2521 }
2522 }
2523
junyulaiebd15162021-03-03 12:09:05 +08002524 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002525 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002526 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002527 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002528 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002529
Serik Beketayev05130302021-01-15 16:47:25 -08002530 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002531 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002532 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2533 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002534 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002535 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002536 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002537 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2538 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002539 }
2540 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002541 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002542 }
2543
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002544 @Override
junyulaiebd15162021-03-03 12:09:05 +08002545 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002546 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002547 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002548 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002549
2550 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2551 for (Network network : getAllNetworks()) {
2552 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002553 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002554 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2555 // NetworkCapabilities, which may contain UIDs of apps to which the
2556 // network applies. Should the UIDs be cleared so as not to leak or
2557 // interfere ?
2558 result.add(nai.getNetworkStateSnapshot());
2559 }
2560 }
2561 return result;
2562 }
2563
2564 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002565 public boolean isActiveNetworkMetered() {
2566 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002567
Qingxi Lib2748102020-01-08 12:51:49 -08002568 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002569 if (caps != null) {
2570 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2571 } else {
2572 // Always return the most conservative value
2573 return true;
2574 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002575 }
2576
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002577 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002578 * Ensures that the system cannot call a particular method.
2579 */
2580 private boolean disallowedBecauseSystemCaller() {
2581 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002582 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2583 // for devices launched with Q and above. However, existing devices upgrading to Q and
2584 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002585 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002586 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002587 log("This method exists only for app backwards compatibility"
2588 + " and must not be called by system services.");
2589 return true;
2590 }
2591 return false;
2592 }
2593
paulhub2c28682021-08-18 18:35:54 +08002594 private int getAppUid(final String app, final UserHandle user) {
2595 final PackageManager pm =
2596 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2597 final long token = Binder.clearCallingIdentity();
2598 try {
2599 return pm.getPackageUid(app, 0 /* flags */);
2600 } catch (PackageManager.NameNotFoundException e) {
2601 return -1;
2602 } finally {
2603 Binder.restoreCallingIdentity(token);
2604 }
2605 }
2606
2607 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2608 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2609 if (getAppUid(packageName, user) != callingUid) {
2610 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2611 }
2612 }
2613
Lorenzo Colitti23862912018-09-28 11:31:55 +09002614 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002615 * Ensure that a network route exists to deliver traffic to the specified
2616 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002617 * @param networkType the type of the network over which traffic to the
2618 * specified host is to be routed
2619 * @param hostAddress the IP address of the host to which the route is
2620 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002621 * @return {@code true} on success, {@code false} on failure
2622 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002623 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002624 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2625 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002626 if (disallowedBecauseSystemCaller()) {
2627 return false;
2628 }
paulhub2c28682021-08-18 18:35:54 +08002629 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002630 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002631 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002632 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002633 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002634
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002635 InetAddress addr;
2636 try {
2637 addr = InetAddress.getByAddress(hostAddress);
2638 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002639 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002640 return false;
2641 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002642
The Android Open Source Project28527d22009-03-03 19:31:44 -08002643 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002644 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002645 return false;
2646 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002647
2648 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2649 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002650 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002651 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2652 } else {
2653 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2654 }
2655 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002656 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002657
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002658 DetailedState netState;
2659 synchronized (nai) {
2660 netState = nai.networkInfo.getDetailedState();
2661 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002662
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002663 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002664 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002665 log("requestRouteToHostAddress on down network "
2666 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002667 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002668 }
2669 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002670 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002671
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002672 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002673 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002674 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002675 LinkProperties lp;
2676 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002677 synchronized (nai) {
2678 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002679 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002680 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002681 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002682 if (DBG) {
2683 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2684 }
Wink Saville32506bc2013-06-29 21:10:57 -07002685 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002686 } finally {
2687 Binder.restoreCallingIdentity(token);
2688 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002689 }
2690
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002691 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002692 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002693 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002694 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002695 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002696 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002697 if (bestRoute.getGateway().equals(addr)) {
2698 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002699 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002700 } else {
2701 // if we will connect to this through another route, add a direct route
2702 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002703 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002704 }
2705 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002706 if (DBG) log("Adding legacy route " + bestRoute +
2707 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002708
2709 final String dst = bestRoute.getDestinationLinkAddress().toString();
2710 final String nextHop = bestRoute.hasGateway()
2711 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002712 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002713 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2714 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002715 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002716 return false;
2717 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002718 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002719 }
2720
paulhu7c0a2e62021-01-08 00:51:49 +08002721 class DnsResolverUnsolicitedEventCallback extends
2722 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002723 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002724 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002725 try {
2726 mHandler.sendMessage(mHandler.obtainMessage(
2727 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002728 new PrivateDnsValidationUpdate(event.netId,
2729 InetAddresses.parseNumericAddress(event.ipAddress),
2730 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002731 } catch (IllegalArgumentException e) {
2732 loge("Error parsing ip address in validation event");
2733 }
2734 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002735
2736 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002737 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2738 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002739 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2740 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2741 // event callback for certain nai. e.g. cellular. Register here to pass to
2742 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002743 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002744 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2745 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002746 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002747 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002748 }
2749 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002750
2751 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002752 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2753 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2754 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002755 }
dalyk1720e542018-03-05 12:42:22 -05002756
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002757 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002758 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002759 return this.VERSION;
2760 }
2761
2762 @Override
2763 public String getInterfaceHash() {
2764 return this.HASH;
2765 }
paulhu7c0a2e62021-01-08 00:51:49 +08002766 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002767
2768 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002769 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2770 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002771
paulhu7c0a2e62021-01-08 00:51:49 +08002772 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002773 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002774 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002775 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002776 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002777 }
2778 }
2779
Sudheer Shanka9967d462021-03-18 19:09:25 +00002780 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002781 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002782 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002783 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2784 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002785 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002786 };
2787
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002788 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002789 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002790 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002791 }
2792
paulhu1a407652019-03-22 16:35:06 +08002793 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2794 for (String permission : permissions) {
2795 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2796 return true;
2797 }
2798 }
2799 return false;
2800 }
2801
Paul Jensen83f5d572014-08-29 09:54:01 -04002802 private void enforceInternetPermission() {
2803 mContext.enforceCallingOrSelfPermission(
2804 android.Manifest.permission.INTERNET,
2805 "ConnectivityService");
2806 }
2807
The Android Open Source Project28527d22009-03-03 19:31:44 -08002808 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002809 mContext.enforceCallingOrSelfPermission(
2810 android.Manifest.permission.ACCESS_NETWORK_STATE,
2811 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002812 }
2813
lucaslinc582d502022-01-27 09:07:00 +08002814 private boolean checkAccessPermission(int pid, int uid) {
2815 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2816 == PERMISSION_GRANTED;
2817 }
2818
paulhua6ee2122021-02-22 15:40:43 +08002819 /**
2820 * Performs a strict and comprehensive check of whether a calling package is allowed to
2821 * change the state of network, as the condition differs for pre-M, M+, and
2822 * privileged/preinstalled apps. The caller is expected to have either the
2823 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2824 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2825 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2826 * permission and cannot be revoked. See http://b/23597341
2827 *
2828 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2829 * of this app will be updated to the current time.
2830 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002831 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002832 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2833 == PackageManager.PERMISSION_GRANTED) {
2834 return;
2835 }
2836
2837 if (callingPkg == null) {
2838 throw new SecurityException("Calling package name is null.");
2839 }
2840
2841 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2842 final int uid = mDeps.getCallingUid();
2843 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2844 callingPkg, callingAttributionTag, null /* message */);
2845
2846 if (mode == AppOpsManager.MODE_ALLOWED) {
2847 return;
2848 }
2849
2850 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2851 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2852 return;
2853 }
2854
2855 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2856 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2857 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002858 }
2859
Charles He9369e612017-05-15 17:07:18 +01002860 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002861 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002862 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002863 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002864 }
2865
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08002866 private void enforceSettingsOrUseRestrictedNetworksPermission() {
2867 enforceAnyPermissionOf(mContext,
2868 android.Manifest.permission.NETWORK_SETTINGS,
2869 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2870 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
2871 }
2872
paulhu8e96a752019-08-12 16:25:11 +08002873 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002874 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002875 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002876 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002877 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002878 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002879 }
2880
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002881 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002882 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002883 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002884 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002885 android.Manifest.permission.NETWORK_SETTINGS,
2886 android.Manifest.permission.NETWORK_FACTORY,
2887 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2888 }
2889
2890 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002891 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002892 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002893 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002894 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2895 android.Manifest.permission.NETWORK_FACTORY,
2896 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2897 }
2898
lucaslin69e1aa92022-03-22 18:15:09 +08002899 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2900 return PERMISSION_GRANTED == mContext.checkPermission(
2901 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2902 || PERMISSION_GRANTED == mContext.checkPermission(
2903 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2904 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002905 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002906 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002907 }
2908
Chalard Jean9a396cc2018-02-21 18:43:54 +09002909 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002910 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002911 android.Manifest.permission.NETWORK_SETTINGS,
2912 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002913 }
2914
2915 private boolean checkSettingsPermission(int pid, int uid) {
2916 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002917 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2918 || PERMISSION_GRANTED == mContext.checkPermission(
2919 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002920 }
2921
paulhu8e96a752019-08-12 16:25:11 +08002922 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002923 enforceNetworkStackPermissionOr(mContext,
2924 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002925 }
2926
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002927 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002928 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002929 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002930 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002931 }
2932
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002933 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002934 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002935 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2936 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002937 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002938 }
2939
James Mattis8378aec2021-01-26 14:05:36 -08002940 private void enforceOemNetworkPreferencesPermission() {
2941 mContext.enforceCallingOrSelfPermission(
2942 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2943 "ConnectivityService");
2944 }
2945
James Mattisfa270db2021-05-31 17:11:10 -07002946 private void enforceManageTestNetworksPermission() {
2947 mContext.enforceCallingOrSelfPermission(
2948 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2949 "ConnectivityService");
2950 }
2951
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002952 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002953 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002954 android.Manifest.permission.NETWORK_STACK,
2955 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002956 }
2957
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002958 private boolean checkNetworkStackPermission(int pid, int uid) {
2959 return checkAnyPermissionOf(pid, uid,
2960 android.Manifest.permission.NETWORK_STACK,
2961 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2962 }
2963
paulhu1a407652019-03-22 16:35:06 +08002964 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2965 return checkAnyPermissionOf(pid, uid,
2966 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002967 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2968 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002969 }
2970
Paul Hu8fc2a552022-05-04 18:44:42 +08002971 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
2972 boolean checkUidsAllowedList) {
2973 if (PermissionUtils.checkAnyPermissionOf(mContext,
2974 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
2975 return true;
2976 }
2977
2978 // fallback to ConnectivityInternalPermission
2979 // TODO: Remove this fallback check after all apps have declared
2980 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2981 if (PermissionUtils.checkAnyPermissionOf(mContext,
2982 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
2983 return true;
2984 }
2985
2986 // Check whether uid is in allowed on restricted networks list.
2987 if (checkUidsAllowedList
2988 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
2989 return true;
2990 }
2991 return false;
2992 }
2993
2994 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
2995 final int callingUid = mDeps.getCallingUid();
2996 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
2997 throw new SecurityException("ConnectivityService: user " + callingUid
2998 + " has no permission to access restricted network.");
2999 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003000 }
3001
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003002 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003003 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003004 }
3005
Roshan Pius98f59ec2021-02-23 08:47:39 -08003006 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3007 return PERMISSION_GRANTED == mContext.checkPermission(
3008 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3009 }
3010
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003011 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003012 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003013 }
3014
3015 private void sendInetConditionBroadcast(NetworkInfo info) {
3016 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3017 }
3018
Wink Saville4f0de1e2011-08-04 15:01:58 -07003019 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003020 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003021 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003022 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003023 if (info.isFailover()) {
3024 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3025 info.setFailover(false);
3026 }
3027 if (info.getReason() != null) {
3028 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3029 }
3030 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003031 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3032 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003033 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003034 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003035 return intent;
3036 }
3037
3038 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3039 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3040 }
3041
Michael Groover73f69482023-01-27 11:01:25 -06003042 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3043 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003044 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3045 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003046 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003047 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003048 if (!mSystemReady
3049 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003050 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003051 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003052 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003053 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003054 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003055 }
3056
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003057 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003058 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003059 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003060 final NetworkInfo ni = intent.getParcelableExtra(
3061 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003062 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3063 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003064 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003065 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003066 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003067 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003068 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003069 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003070 } finally {
3071 Binder.restoreCallingIdentity(ident);
3072 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003073 }
3074 }
3075
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003076 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3077 NetworkInfo info) {
3078 // Delivery group policy APIs are only available on U+.
3079 if (!SdkLevel.isAtLeastU()) return;
3080
3081 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3082 try {
3083 // This allows us to discard older broadcasts still waiting to be delivered
3084 // which have the same namespace and key.
3085 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3086 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3087 createDeliveryGroupKeyForConnectivityAction(info));
Sudheer Shanka74fe7172023-01-24 19:33:06 +00003088 optsShim.setDeferUntilActive(true);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003089 } catch (UnsupportedApiLevelException e) {
3090 Log.wtf(TAG, "Using unsupported API" + e);
3091 }
3092 }
3093
3094 @VisibleForTesting
3095 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3096 final StringBuilder sb = new StringBuilder();
3097 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3098 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3099 sb.append(info.getExtraInfo());
3100 return sb.toString();
3101 }
3102
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003103 /**
Aaron Huang96011892020-06-27 07:18:23 +08003104 * Called by SystemServer through ConnectivityManager when the system is ready.
3105 */
3106 @Override
3107 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003108 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003109 throw new SecurityException("Calling Uid is not system uid.");
3110 }
3111 systemReadyInternal();
3112 }
3113
3114 /**
3115 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003116 */
3117 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003118 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003119 // Load flags after PackageManager is ready to query module version
3120 mFlags.loadFlags(mDeps, mContext);
3121
Aaron Huang9a57acf2020-12-08 10:03:29 +08003122 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3123 // listening network request which is sent by MultipathPolicyTracker won't be added
3124 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3125 // be called after PermissionMonitor#startMonitoring().
3126 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3127 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3128 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003129 final ConditionVariable startMonitoringDone = new ConditionVariable();
3130 mHandler.post(() -> {
3131 mPermissionMonitor.startMonitoring();
3132 startMonitoringDone.open();
3133 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003134 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003135 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003136
Hugo Benichie5220992017-04-26 14:53:28 +09003137 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003138 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003139 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003140 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003141 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003142 }
3143 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003144
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003145 // Create network requests for always-on networks.
3146 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003147
3148 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003149 // Note that updating can be skipped here if the list is empty only because no uid
3150 // rules are applied before system ready. Normally, the empty uid list means to clear
3151 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003152 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3153 updateMobileDataPreferredUids();
3154 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003155
3156 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3157 if (SdkLevel.isAtLeastT()) {
3158 mBpfNetMaps.setPullAtomCallback(mContext);
3159 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003160 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3161 // have permission problem. While CV#block() is unbounded in time and can in principle block
3162 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3163 // could have blocked forever too.
3164 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003165 }
3166
The Android Open Source Project28527d22009-03-03 19:31:44 -08003167 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003168 * Start listening for default data network activity state changes.
3169 */
3170 @Override
3171 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003172 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003173 }
3174
3175 /**
3176 * Stop listening for default data network activity state changes.
3177 */
3178 @Override
3179 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003180 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003181 }
3182
3183 /**
3184 * Check whether the default network radio is currently active.
3185 */
3186 @Override
3187 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003188 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003189 }
3190
3191 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003192 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003193 * and set it on it's iface.
3194 */
Junyu Lai970963e2022-10-25 15:46:47 +08003195 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003196 final String iface = newLp.getInterfaceName();
3197 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003198 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003199 // Silently ignore unset MTU value.
3200 return;
3201 }
Hansen Kurli04252032022-12-07 11:21:49 +00003202 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3203 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3204 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003205 return;
3206 }
Hansen Kurli04252032022-12-07 11:21:49 +00003207 // Cannot set MTU without interface name
3208 if (TextUtils.isEmpty(iface)) {
3209 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003210 return;
3211 }
sy.yun4aa73922013-09-02 05:24:09 +09003212
Hansen Kurli04252032022-12-07 11:21:49 +00003213 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3214 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003215 return;
3216 }
3217
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003218 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003219 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003220 mNetd.interfaceSetMtu(iface, mtu);
3221 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003222 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003223 }
3224 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003225
Chenbo Feng15416292018-11-08 17:36:21 -08003226 @VisibleForTesting
3227 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003228
Junyu Lai970963e2022-10-25 15:46:47 +08003229 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003230 String[] values = null;
3231 if (tcpBufferSizes != null) {
3232 values = tcpBufferSizes.split(",");
3233 }
3234
3235 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003236 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003237 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3238 values = tcpBufferSizes.split(",");
3239 }
3240
3241 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3242
3243 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003244 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003245
Chenbo Feng15416292018-11-08 17:36:21 -08003246 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3247 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3248 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003249 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003250 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003251 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003252 }
3253 }
3254
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003255 @Override
3256 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003257 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003258 NETWORK_RESTORE_DELAY_PROP_NAME);
3259 if(restoreDefaultNetworkDelayStr != null &&
3260 restoreDefaultNetworkDelayStr.length() != 0) {
3261 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003262 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003263 } catch (NumberFormatException e) {
3264 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003265 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003266 // if the system property isn't set, use the value for the apn type
3267 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3268
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003269 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3270 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003271 }
3272 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003273 }
3274
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003275 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003276 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003277 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003278 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003279 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003280 // Start gathering diagnostic information.
3281 netDiags.add(new NetworkDiagnostics(
3282 nai.network,
3283 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003284 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003285 DIAG_TIME_MS));
3286 }
3287
3288 for (NetworkDiagnostics netDiag : netDiags) {
3289 pw.println();
3290 netDiag.waitForMeasurements();
3291 netDiag.dump(pw);
3292 }
3293 }
3294
The Android Open Source Project28527d22009-03-03 19:31:44 -08003295 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003296 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3297 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003298 if (!checkDumpPermission(mContext, TAG, writer)) return;
3299
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003300 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003301 }
3302
lucaslin99473f62020-12-10 15:10:54 +08003303 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3304 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3305 != PackageManager.PERMISSION_GRANTED) {
3306 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003307 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003308 + " due to missing android.permission.DUMP permission");
3309 return false;
3310 } else {
3311 return true;
3312 }
3313 }
3314
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003315 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003316 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003317
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003318 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003319 dumpNetworkDiagnostics(pw);
3320 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003321 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003322 dumpNetworks(pw);
3323 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003324 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003325 dumpNetworkRequests(pw);
3326 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003327 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3328 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3329 dumpTrafficController(pw, fd, verbose);
3330 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003331 }
Erik Kline9647f382015-06-05 17:47:34 +09003332
Junyu Lai0da479b2022-04-20 15:06:29 +08003333 pw.println("NetworkProviders for:");
3334 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003335 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003336 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003337 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003338 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003339 pw.println();
3340
Chalard Jean5b409c72021-02-04 13:12:59 +09003341 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003342 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003343 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003344 pw.println("none");
3345 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003346 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003347 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003348 pw.println();
3349
James Mattis8b298a02021-06-01 22:34:04 -07003350 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003351 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003352 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003353 pw.decreaseIndent();
3354 pw.println();
3355
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003356 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003357 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003358 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003359 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003360 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003361
junyulaif2c67e42018-08-07 19:50:45 +08003362 pw.println("Status for known UIDs:");
3363 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003364 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003365 for (int i = 0; i < size; i++) {
3366 // Don't crash if the array is modified while dumping in bugreports.
3367 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003368 final int uid = mUidBlockedReasons.keyAt(i);
3369 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3370 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003371 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003372 } catch (ArrayIndexOutOfBoundsException e) {
3373 pw.println(" ArrayIndexOutOfBoundsException");
3374 } catch (ConcurrentModificationException e) {
3375 pw.println(" ConcurrentModificationException");
3376 }
3377 }
3378 pw.println();
3379 pw.decreaseIndent();
3380
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003381 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003382 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003383 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003384 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003385 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003386
Junyu Lai0da479b2022-04-20 15:06:29 +08003387 pw.println("Network Offers:");
3388 pw.increaseIndent();
3389 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3390 pw.println(offerInfo.offer);
3391 }
3392 pw.decreaseIndent();
3393 pw.println();
3394
Robert Greenwalt94e22142014-07-30 16:31:24 -07003395 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003396
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003397 pw.println();
markchien5e866652019-09-30 14:40:57 +08003398 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003399
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003400 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003401 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003402
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003403 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003404
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003405 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003406 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003407 pw.println("mNetworkRequestInfoLogs (most recent first):");
3408 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003409 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003410 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003411
3412 pw.println();
3413 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3414 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003415 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003416 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003417
3418 pw.println();
3419 pw.println("NetTransition WakeLock activity (most recent first):");
3420 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003421 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3422 pw.println("total releases: " + mTotalWakelockReleases);
3423 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3424 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3425 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3426 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3427 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3428 }
James Mattiscb1e0362021-04-06 17:07:42 -07003429 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003430
3431 pw.println();
3432 pw.println("bandwidth update requests (by uid):");
3433 pw.increaseIndent();
3434 synchronized (mBandwidthRequests) {
3435 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3436 pw.println("[" + mBandwidthRequests.keyAt(i)
3437 + "]: " + mBandwidthRequests.valueAt(i));
3438 }
3439 }
3440 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003441 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003442
James Mattiscb1e0362021-04-06 17:07:42 -07003443 pw.println();
3444 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3445 pw.increaseIndent();
3446 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003447 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003448 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003449
3450 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003451
3452 pw.println();
3453 pw.println("Permission Monitor:");
3454 pw.increaseIndent();
3455 mPermissionMonitor.dump(pw);
3456 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003457
3458 pw.println();
3459 pw.println("Legacy network activity:");
3460 pw.increaseIndent();
3461 mNetworkActivityTracker.dump(pw);
3462 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003463 }
3464
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003465 private void dumpNetworks(IndentingPrintWriter pw) {
3466 for (NetworkAgentInfo nai : networksSortedById()) {
3467 pw.println(nai.toString());
3468 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003469 pw.println("Nat464Xlat:");
3470 pw.increaseIndent();
3471 nai.dumpNat464Xlat(pw);
3472 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003473 pw.println(String.format(
3474 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3475 nai.numForegroundNetworkRequests(),
3476 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3477 nai.numBackgroundNetworkRequests(),
3478 nai.numNetworkRequests()));
3479 pw.increaseIndent();
3480 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3481 pw.println(nai.requestAt(i).toString());
3482 }
3483 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003484 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003485 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003486 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003487 pw.decreaseIndent();
3488 pw.decreaseIndent();
3489 }
3490 }
3491
James Mattis8b298a02021-06-01 22:34:04 -07003492 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3493 if (!mProfileNetworkPreferences.isEmpty()) {
3494 pw.println("Profile preferences:");
3495 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003496 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003497 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003498 }
James Mattis8b298a02021-06-01 22:34:04 -07003499 if (!mOemNetworkPreferences.isEmpty()) {
3500 pw.println("OEM preferences:");
3501 pw.increaseIndent();
3502 pw.println(mOemNetworkPreferences);
3503 pw.decreaseIndent();
3504 }
3505 if (!mMobileDataPreferredUids.isEmpty()) {
3506 pw.println("Mobile data preferred UIDs:");
3507 pw.increaseIndent();
3508 pw.println(mMobileDataPreferredUids);
3509 pw.decreaseIndent();
3510 }
James Mattis45d81842021-01-10 14:24:24 -08003511
James Mattis8b298a02021-06-01 22:34:04 -07003512 pw.println("Default requests:");
3513 pw.increaseIndent();
3514 dumpPerAppDefaultRequests(pw);
3515 pw.decreaseIndent();
3516 }
3517
3518 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003519 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3520 if (mDefaultRequest == defaultRequest) {
3521 continue;
3522 }
3523
James Mattis8b298a02021-06-01 22:34:04 -07003524 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3525 final String networkOutput;
3526 if (null == satisfier) {
3527 networkOutput = "null";
3528 } else if (mNoServiceNetwork.equals(satisfier)) {
3529 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003530 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003531 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003532 }
James Mattis8b298a02021-06-01 22:34:04 -07003533 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3534 ? "" : " asUid: " + defaultRequest.mAsUid;
3535 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3536 + defaultRequest.mPid + asUidString + "]";
3537 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3538 + " Preference order: " + defaultRequest.mPreferenceOrder
3539 + " Tracked UIDs: " + defaultRequest.getUids();
3540 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003541 }
3542 }
3543
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003544 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003545 NetworkRequestInfo[] infos = null;
3546 while (infos == null) {
3547 try {
3548 infos = requestsSortedById();
3549 } catch (ConcurrentModificationException e) {
3550 // mNetworkRequests should only be accessed from handler thread, except dump().
3551 // As dump() is never called in normal usage, it would be needlessly expensive
3552 // to lock the collection only for its benefit. Instead, retry getting the
3553 // requests if ConcurrentModificationException is thrown during dump().
3554 }
3555 }
3556 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003557 pw.println(nri.toString());
3558 }
3559 }
3560
Ken Chene6d511f2022-01-25 11:10:42 +08003561 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3562 boolean verbose) {
3563 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003564 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003565 } catch (ServiceSpecificException e) {
3566 pw.println(e.getMessage());
3567 } catch (IOException e) {
3568 loge("Dump BPF maps failed, " + e);
3569 }
3570 }
3571
Chalard Jean524f0b12021-10-25 21:11:56 +09003572 private void dumpAllRequestInfoLogsToLogcat() {
3573 try (PrintWriter logPw = new PrintWriter(new Writer() {
3574 @Override
3575 public void write(final char[] cbuf, final int off, final int len) {
3576 // This method is called with 0-length and 1-length arrays for empty strings
3577 // or strings containing only the DEL character.
3578 if (len <= 1) return;
3579 Log.e(TAG, new String(cbuf, off, len));
3580 }
3581 @Override public void flush() {}
3582 @Override public void close() {}
3583 })) {
3584 mNetworkRequestInfoLogs.dump(logPw);
3585 }
3586 }
3587
Hugo Benichia480ba52018-09-03 08:19:02 +09003588 /**
3589 * Return an array of all current NetworkAgentInfos sorted by network id.
3590 */
3591 private NetworkAgentInfo[] networksSortedById() {
3592 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003593 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003594 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003595 return networks;
3596 }
3597
3598 /**
3599 * Return an array of all current NetworkRequest sorted by request id.
3600 */
James Mattis258ea3c2020-11-15 15:04:40 -08003601 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003602 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003603 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003604 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003605 // Sort the array based off the NRI containing the min requestId in its requests.
3606 Arrays.sort(requests,
3607 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3608 Comparator.comparingInt(req -> req.requestId)).requestId
3609 )
3610 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003611 return requests;
3612 }
3613
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003614 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003615 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003616 if (officialNai != null && officialNai.equals(nai)) return true;
3617 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003618 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003619 " - " + nai);
3620 }
3621 return false;
3622 }
3623
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003624 private boolean isDisconnectRequest(Message msg) {
3625 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3626 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3627 return info.getState() == NetworkInfo.State.DISCONNECTED;
3628 }
3629
Robert Greenwalt2034b912009-08-12 16:08:25 -07003630 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003631 private class NetworkStateTrackerHandler extends Handler {
3632 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003633 super(looper);
3634 }
3635
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003636 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003637 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3638 final NetworkAgentInfo nai = arg.first;
3639 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003640 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003641 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003642 }
3643 return;
3644 }
3645
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003646 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003647 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003648 return;
3649 }
3650
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003651 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003652 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003653 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3654 final NetworkCapabilities sanitized =
3655 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003656 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003657 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003658 break;
3659 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003660 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003661 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003662 processLinkPropertiesFromAgent(nai, newLp);
3663 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003664 break;
3665 }
3666 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003667 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003668 updateNetworkInfo(nai, info);
3669 break;
3670 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003671 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003672 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003673 break;
3674 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003675 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003676 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003677 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003678 // Note that if the NAI had been connected, this would affect the
3679 // score, and therefore would require re-mixing the score and performing
3680 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003681 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003682 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3683 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003684 // Mark the network as temporarily accepting partial connectivity so that it
3685 // will be validated (and possibly become default) even if it only provides
3686 // partial internet access. Note that if user connects to partial connectivity
3687 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3688 // out of wifi coverage) and if the same wifi is available again, the device
3689 // will auto connect to this wifi even though the wifi has "no internet".
3690 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003691 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003692 break;
3693 }
junyulai011b1f12019-01-03 18:50:15 +08003694 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003695 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003696 break;
3697 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003698 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003699 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003700 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003701
3702 if (isLegacyLockdownNai(nai)
3703 && (underlying == null || underlying.size() != 1)) {
3704 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3705 + " must have exactly one underlying network: " + underlying);
3706 }
3707
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003708 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3709 nai.declaredUnderlyingNetworks = (underlying != null)
3710 ? underlying.toArray(new Network[0]) : null;
3711
3712 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3713 if (DBG) {
3714 log(nai.toShortString() + " changed underlying networks to "
3715 + Arrays.toString(nai.declaredUnderlyingNetworks));
3716 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003717 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003718 notifyIfacesChangedForNetworkStats();
3719 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003720 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003721 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003722 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3723 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3724 nai.teardownDelayMs = msg.arg1;
3725 } else {
3726 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3727 }
Chalard Jean550b5212021-03-05 23:07:53 +09003728 break;
3729 }
3730 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3731 nai.setLingerDuration((int) arg.second);
3732 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003733 }
Tyler Wear72388212021-09-09 14:49:02 -07003734 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3735 DscpPolicy policy = (DscpPolicy) arg.second;
3736 if (mDscpPolicyTracker != null) {
3737 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3738 }
3739 break;
3740 }
3741 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3742 if (mDscpPolicyTracker != null) {
3743 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3744 }
3745 break;
3746 }
3747 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3748 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003749 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003750 }
3751 break;
3752 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003753 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09003754 if (!nai.isCreated()) {
3755 Log.d(TAG, "unregisterAfterReplacement on uncreated " + nai.toShortString()
3756 + ", tearing down instead");
3757 teardownUnneededNetwork(nai);
3758 break;
3759 }
3760
3761 if (nai.isDestroyed()) {
3762 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
3763 + ", ignoring");
3764 break;
3765 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003766
3767 final int timeoutMs = (int) arg.second;
3768 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3769 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3770 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3771 }
3772
3773 // Marking a network awaiting replacement is used to ensure that any requests
3774 // satisfied by the network do not switch to another network until a
3775 // replacement is available or the wait for a replacement times out.
3776 // If the network is inactive (i.e., nascent or lingering), then there are no
3777 // such requests, and there is no point keeping it. Just tear it down.
3778 // Note that setLingerDuration(0) cannot be used to do this because the network
3779 // could be nascent.
3780 nai.clearInactivityState();
3781 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3782 Log.d(TAG, nai.toShortString()
3783 + " marked awaiting replacement is unneeded, tearing down instead");
3784 teardownUnneededNetwork(nai);
3785 break;
3786 }
3787
3788 Log.d(TAG, "Marking " + nai.toShortString()
3789 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3790 destroyNativeNetwork(nai);
3791
3792 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3793 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3794 // consider the fact that the network could already have disconnected or been
3795 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3796 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3797 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3798 mKeepaliveTracker.handleStopAllKeepalives(nai,
3799 SocketKeepalive.ERROR_INVALID_NETWORK);
3800
3801 nai.updateScoreForNetworkAgentUpdate();
3802 // This rematch is almost certainly not going to result in any changes, because
3803 // the destroyed flag is only just above the "current satisfier wins"
3804 // tie-breaker. But technically anything that affects scoring should rematch.
3805 rematchAllNetworksAndRequests();
3806 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3807 break;
3808 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003809 }
3810 }
3811
3812 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003813 final int netId = msg.arg2;
3814 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003815 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003816 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003817 switch (msg.what) {
3818 default:
3819 return false;
lucasline117e2e2019-10-22 18:27:33 +08003820 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003821 if (nai == null) {
3822 break;
3823 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003824 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3825 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003826 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003827 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003828 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003829 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003830 if (probePrivateDnsCompleted) {
3831 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3832 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003833 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003834 }
3835 // Only show the notification when the private DNS is broken and the
3836 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003837 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003838 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3839 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003840 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003841 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3842 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3843 // private DNS is broken, it means this network is being reevaluated.
3844 // Either probing private DNS is not necessary any more or it hasn't been
3845 // done yet. In either case, the networkCapabilities should be updated to
3846 // reflect the new status.
3847 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003848 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003849 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003850 }
3851 break;
3852 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003853 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003854 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3855
Erik Kline31b4a9e2018-01-11 21:07:29 +09003856 if (nai == null) break;
3857
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003858 handleNetworkTested(nai, results.mTestResult,
3859 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003860 break;
3861 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003862 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003863 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003864 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003865 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003866 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003867 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003868 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3869 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003870 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003871 if (nai == null) {
3872 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3873 break;
3874 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003875 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003876 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003877 (PendingIntent) msg.obj,
3878 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003879 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003880 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003881 break;
3882 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003883 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003884 if (nai == null) break;
3885
Erik Kline9a62f012018-03-21 07:18:33 -07003886 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003887 break;
3888 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003889 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003890 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003891 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003892 break;
3893 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003894 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003895 return true;
3896 }
3897
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003898 private void handleNetworkTested(
3899 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09003900 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
3901 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09003902 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003903
3904 // If there is any kind of working networking, then the NAI has been evaluated
3905 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
3906 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09003907 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003908 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09003909 // Because of b/245893397, if the score is updated when updateCapabilities is called,
3910 // any callback that receives onAvailable for that rematch receives an extra caps
3911 // callback. To prevent that, update the score in the agent so the updates below won't
3912 // see an update to both caps and score at the same time.
3913 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003914 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
3915
he_won.hwang881307a2022-03-15 21:23:52 +09003916 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3917 // Assume the validation failure is due to a temporary failure after roaming
3918 // and ignore it. NetworkMonitor will continue to retry validation. If it
3919 // continues to fail after the block timeout expires, the network will be
3920 // marked unvalidated. If it succeeds, then validation state will not change.
3921 return;
3922 }
3923
Chalard Jean254bd162022-08-25 13:04:51 +09003924 final boolean wasValidated = nai.isValidated();
3925 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09003926 final boolean wasPortal = nai.captivePortalDetected();
3927 nai.setPartialConnectivity(partial);
3928 nai.setCaptivePortalDetected(portal);
3929 nai.updateScoreForNetworkAgentUpdate();
3930 final boolean partialConnectivityChanged = (wasPartial != partial);
3931 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003932
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003933 if (DBG) {
3934 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3935 ? " with redirect to " + redirectUrl
3936 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003937 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003938 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09003939 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003940 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003941 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003942 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003943 if (valid) {
3944 handleFreshlyValidatedNetwork(nai);
3945 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3946 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003947 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003948 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003949 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003950 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003951 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003952 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003953 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003954 NotificationType.PRIVATE_DNS_BROKEN);
3955 // If network becomes valid, the hasShownBroken should be reset for
3956 // that network so that the notification will be fired when the private
3957 // DNS is broken again.
3958 nai.networkAgentConfig.hasShownBroken = false;
3959 }
3960 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003961 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09003962 } else if (portalChanged) {
3963 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3964 == getCaptivePortalMode()) {
3965 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3966 nai.onPreventAutomaticReconnect();
3967 teardownUnneededNetwork(nai);
3968 return;
3969 } else {
3970 updateCapabilitiesForNetwork(nai);
3971 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09003972 } else if (becameEvaluated) {
3973 // If valid or partial connectivity changed, updateCapabilities* has
3974 // done the rematch.
3975 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003976 }
3977 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003978
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003979 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003980 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003981 nai.onValidationStatusChanged(
3982 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3983 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003984
3985 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09003986 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003987 // immediately. Re-notify partial connectivity silently if no internet
3988 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09003989 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003990 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003991 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
3992 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003993 }
3994
Chalard Jean254bd162022-08-25 13:04:51 +09003995 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003996 handleNetworkUnvalidated(nai);
3997 }
3998 }
3999
Calvin Ondada1452016-10-11 15:10:46 -07004000 private int getCaptivePortalMode() {
4001 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004002 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4003 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004004 }
4005
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004006 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4007 switch (msg.what) {
4008 default:
4009 return false;
4010 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4011 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4012 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4013 handleLingerComplete(nai);
4014 }
4015 break;
4016 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004017 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4018 handleNetworkAgentRegistered(msg);
4019 break;
4020 }
4021 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4022 handleNetworkAgentDisconnected(msg);
4023 break;
4024 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004025 }
4026 return true;
4027 }
4028
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004029 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004030 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004031 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004032 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004033 maybeHandleNetworkAgentMessage(msg);
4034 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004035 }
4036 }
4037
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004038 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004039 private final int mNetId;
4040 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004041
4042 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004043 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004044 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004045 }
4046
4047 @Override
4048 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4049 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004050 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004051 }
4052
4053 @Override
4054 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004055 // Legacy version of notifyNetworkTestedWithExtras.
4056 // Would only be called if the system has a NetworkStack module older than the
4057 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004058 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004059 }
4060
4061 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004062 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004063 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4064 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004065 final Message msg = mTrackerHandler.obtainMessage(
4066 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004067 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004068 new NetworkTestedResults(
4069 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004070 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004071
4072 // Invoke ConnectivityReport generation for this Network test event.
4073 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4074 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004075
Cody Kestingf1120be2020-08-03 18:01:40 -07004076 // NetworkMonitor reports the network validation result as a bitmask while
4077 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4078 // logical value for ConnectivityDiagnostics.
4079 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4080 p.result);
4081
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004082 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004083 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004084 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4085 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4086
Aaron Huang959d3642021-01-21 15:47:41 +08004087 ConnectivityReportEvent reportEvent =
4088 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4089 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004090 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004091 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004092 }
4093
4094 @Override
4095 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4096 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4097 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004098 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004099 }
4100
4101 @Override
lucasline117e2e2019-10-22 18:27:33 +08004102 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4103 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4104 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004105 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004106 }
4107
4108 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004109 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4110 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4111 EVENT_CAPPORT_DATA_CHANGED,
4112 0, mNetId, data));
4113 }
4114
4115 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004116 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004117 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004118 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004119
4120 final PendingIntent pendingIntent;
4121 // Only the system server can register notifications with package "android"
4122 final long token = Binder.clearCallingIdentity();
4123 try {
paulhu7746e4e2020-06-09 19:07:03 +08004124 pendingIntent = PendingIntent.getBroadcast(
4125 mContext,
4126 0 /* requestCode */,
4127 intent,
4128 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004129 } finally {
4130 Binder.restoreCallingIdentity(token);
4131 }
4132 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4133 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004134 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004135 }
4136
4137 @Override
4138 public void hideProvisioningNotification() {
4139 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004140 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004141 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004142
4143 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004144 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004145 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004146 }
4147
4148 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004149 public int getInterfaceVersion() {
4150 return this.VERSION;
4151 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004152
4153 @Override
4154 public String getInterfaceHash() {
4155 return this.HASH;
4156 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004157 }
4158
Cody Kestingf1120be2020-08-03 18:01:40 -07004159 /**
4160 * Converts the given NetworkMonitor-specific validation result bitmask to a
4161 * ConnectivityDiagnostics-specific validation result int.
4162 */
4163 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4164 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4165 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4166 }
4167 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4168 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4169 }
4170 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4171 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4172 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4173 }
4174
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004175 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004176 log("Data stall detected with methods: " + p.detectionMethod);
4177
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004178 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004179 int detectionMethod = 0;
4180 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4181 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4182 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4183 }
4184 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4185 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4186 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4187 p.tcpMetricsCollectionPeriodMillis);
4188 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004189 }
4190
Cody Kestingf53a0752020-04-15 12:33:28 -07004191 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004192 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004193 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004194
4195 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4196 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4197 // the cost of going through two handlers.
4198 mConnectivityDiagnosticsHandler.sendMessage(msg);
4199 }
4200
Cody Kestingb37958e2020-05-15 10:36:01 -07004201 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4202 return (p.detectionMethod & detectionMethod) != 0;
4203 }
4204
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004205 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4206 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004207 }
4208
Erik Klinea73af002018-06-26 18:53:43 +09004209 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4210 if (nai == null) return;
4211 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4212 // in order to restart a validation pass from within netd.
4213 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4214 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004215 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004216 }
4217 }
4218
Erik Kline31b4a9e2018-01-11 21:07:29 +09004219 private void handlePrivateDnsSettingsChanged() {
4220 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4221
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004222 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004223 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004224 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004225 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4226 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004227 }
4228 }
4229
Erik Kline9a62f012018-03-21 07:18:33 -07004230 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4231 // Private DNS only ever applies to networks that might provide
4232 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004233 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004234
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004235 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004236 // schedule DNS resolutions. If a DNS resolution is required the
4237 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004238 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004239
4240 // With Private DNS bypass support, we can proceed to update the
4241 // Private DNS config immediately, even if we're in strict mode
4242 // and have not yet resolved the provider name into a set of IPs.
4243 updatePrivateDns(nai, cfg);
4244 }
4245
4246 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4247 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004248 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004249 }
4250
dalyk1720e542018-03-05 12:42:22 -05004251 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4252 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4253 if (nai == null) {
4254 return;
4255 }
4256 mDnsManager.updatePrivateDnsValidation(update);
4257 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4258 }
4259
paulhu7c0a2e62021-01-08 00:51:49 +08004260 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004261 int prefixLength) {
4262 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4263 if (nai == null) return;
4264
paulhu7c0a2e62021-01-08 00:51:49 +08004265 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4266 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004267
4268 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004269 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004270 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004271 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004272 prefixLength);
4273 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004274 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004275 return;
4276 }
4277 }
4278
Lorenzo Colittid523d142020-04-01 20:16:30 +09004279 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004280 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4281 }
4282
Hai Shalome58bdc62021-01-11 18:45:34 -08004283 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004284 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004285 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004286 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4287 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4288 }
4289
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004290 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004291 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004292 * @param nai the agent info to update
4293 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004294 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004295 */
junyulai2b6f0c22021-02-03 20:15:30 +08004296 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4297 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4298 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004299 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004300 // one lingered request, set inactive.
4301 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004302 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004303 if (DBG) log("Unsetting inactive " + nai.toShortString());
4304 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004305 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004306 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004307 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004308 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4309 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004310 }
junyulai2b6f0c22021-02-03 20:15:30 +08004311 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004312 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004313 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004314 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004315 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004316 }
4317
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004318 private void handleNetworkAgentRegistered(Message msg) {
4319 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4320 if (!mNetworkAgentInfos.contains(nai)) {
4321 return;
4322 }
4323
4324 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4325 if (VDBG) log("NetworkAgent registered");
4326 } else {
4327 loge("Error connecting NetworkAgent");
4328 mNetworkAgentInfos.remove(nai);
4329 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004330 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004331 synchronized (mNetworkForNetId) {
4332 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004333 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004334 mNetIdManager.releaseNetId(nai.network.getNetId());
4335 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004336 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004337 }
4338 }
4339 }
Paul Jensend5f53392014-11-25 15:26:53 -05004340
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004341 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004342 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004343 }
4344
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004345 @VisibleForTesting
4346 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004347 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004348 if (SdkLevel.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004349
4350 // If the network never roamed, return false. The check below is not sufficient if time
4351 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4352 if (nai.lastRoamTime == 0) return false;
4353
he_won.hwang881307a2022-03-15 21:23:52 +09004354 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4355 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004356 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004357 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004358 final long currentTimeMs = SystemClock.elapsedRealtime();
4359 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004360 if (timeSinceLastRoam <= blockTimeOut) {
4361 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4362 return true;
4363 }
4364 }
4365 return false;
4366 }
4367
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004368 private void handleNetworkAgentDisconnected(Message msg) {
4369 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004370 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004371 }
4372
Chalard Jeand9fffc32018-05-11 20:19:20 +09004373 // Destroys a network, remove references to it from the internal state managed by
4374 // ConnectivityService, free its interfaces and clean up.
4375 // Must be called on the Handler thread.
4376 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004377 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004378
4379 if (!mNetworkAgentInfos.contains(nai)) return;
4380
Chalard Jeand9fffc32018-05-11 20:19:20 +09004381 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004382 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004383 }
lucaslinb25c9a62019-02-12 15:30:13 +08004384 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004385 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004386 // A network agent has disconnected.
4387 // TODO - if we move the logic to the network agent (have them disconnect
4388 // because they lost all their requests or because their score isn't good)
4389 // then they would disconnect organically, report their new state and then
4390 // disconnect the channel.
4391 if (nai.networkInfo.isConnected()) {
4392 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4393 null, null);
4394 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004395 final boolean wasDefault = isDefaultNetwork(nai);
4396 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004397 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004398 }
4399 notifyIfacesChangedForNetworkStats();
4400 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4401 // by other networks that are already connected. Perhaps that can be done by
4402 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4403 // of rematchAllNetworksAndRequests
4404 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004405 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004406
4407 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004408 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4409 // Disable wakeup packet monitoring for each interface.
4410 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4411 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004412 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004413 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004414 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004415 synchronized (mNetworkForNetId) {
4416 // Remove the NetworkAgent, but don't mark the netId as
4417 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004418 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004419 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004420 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004421 // Update allowed network lists in netd. This should be called after removing nai
4422 // from mNetworkAgentInfos.
4423 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004424 // Remove all previously satisfied requests.
4425 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004426 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004427 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004428 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004429 if (currentNetwork != null
4430 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004431 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004432 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4433 // rematch not to keep disconnected agents instead of setting it here ; this
4434 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004435 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004436 for (final NetworkOfferInfo noi : mNetworkOffers) {
4437 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004438 }
James Mattise3ef1912020-12-20 11:09:58 -08004439
Chalard Jean5b409c72021-02-04 13:12:59 +09004440 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004441 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004442 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004443 // network, because while incorrect this is the closest to the old (also
4444 // incorrect) behavior.
4445 mNetworkActivityTracker.updateDataActivityTracking(
4446 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004447 ensureNetworkTransitionWakelock(nai.toShortString());
4448 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004449 }
4450 }
junyulai2b6f0c22021-02-03 20:15:30 +08004451 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004452 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004453 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004454 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004455 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004456 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004457 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004458
4459 // Immediate teardown.
4460 if (nai.teardownDelayMs == 0) {
4461 destroyNetwork(nai);
4462 return;
4463 }
4464
4465 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004466 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304467 try {
4468 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4469 } catch (RemoteException e) {
4470 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4471 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004472 }
4473 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4474 }
4475
4476 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004477 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004478 // Tell netd to clean up the configuration for this network
4479 // (routing rules, DNS, etc).
4480 // This may be slow as it requires a lot of netd shelling out to ip and
4481 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004482 // after we've rematched networks with requests (which might change the default
4483 // network or service a new request from an app), so network traffic isn't interrupted
4484 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004485 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004486 }
Chalard Jean254bd162022-08-25 13:04:51 +09004487 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004488 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4489 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4490 // false if the network was never created.
4491 // TODO: delete when S is no longer supported.
4492 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004493 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004494 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004495 }
4496
Ken Chen6df7a902021-04-09 15:08:42 +08004497 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004498 try {
4499 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004500 final NativeNetworkConfig config;
4501 if (nai.isVPN()) {
4502 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004503 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004504 return false;
4505 }
4506 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4507 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004508 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004509 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004510 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004511 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004512 getNetworkPermission(nai.networkCapabilities),
4513 false /* secure */,
4514 VpnManager.TYPE_VPN_NONE,
4515 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004516 }
Ken Chen6df7a902021-04-09 15:08:42 +08004517 mNetd.networkCreate(config);
4518 mDnsResolver.createNetworkCache(nai.network.getNetId());
4519 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4520 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004521 return true;
4522 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004523 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004524 return false;
4525 }
4526 }
4527
Ken Chen6df7a902021-04-09 15:08:42 +08004528 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004529 if (mDscpPolicyTracker != null) {
4530 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4531 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004532 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004533 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004534 } catch (RemoteException | ServiceSpecificException e) {
4535 loge("Exception destroying network(networkDestroy): " + e);
4536 }
4537 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004538 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004539 } catch (RemoteException | ServiceSpecificException e) {
4540 loge("Exception destroying network: " + e);
4541 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004542 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4543 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4544 // gets created, could add data to DnsManager data structures that will never get deleted.
4545 mDnsManager.removeNetwork(nai.network);
4546
4547 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004548 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004549 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4550 }
4551
Chalard Jean254bd162022-08-25 13:04:51 +09004552 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004553 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004554 }
4555
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004556 // If this method proves to be too slow then we can maintain a separate
4557 // pendingIntent => NetworkRequestInfo map.
4558 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4559 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004560 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4561 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4562 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004563 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004564 return entry.getValue();
4565 }
4566 }
4567 return null;
4568 }
4569
Chalard Jean524f0b12021-10-25 21:11:56 +09004570 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4571 if (SdkLevel.isAtLeastT()) {
4572 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4573 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4574 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4575 // bug is fixed.
4576 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004577 throw new IllegalStateException("This NRI is already registered. New : " + nri
4578 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004579 }
4580 }
4581 }
4582 }
4583
Chalard Jeanac9ace02022-01-26 16:54:05 +09004584 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4585 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004586 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004587 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4588 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004589 }
4590 return false;
4591 }
4592
James Mattisf7027322020-12-13 16:28:14 -08004593 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004594 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004595 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4596 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4597 final NetworkRequestInfo existingRequest =
4598 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004599 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004600 if (DBG) {
4601 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4602 + nri.mRequests.get(0) + " because their intents matched.");
4603 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004604 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004605 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004606 }
Erik Kline05f2b402015-04-30 12:58:40 +09004607 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004608 }
4609
James Mattisf7027322020-12-13 16:28:14 -08004610 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004611 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004612 }
4613
James Mattis3ce3d3c2021-02-09 18:18:28 -08004614 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004615 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004616 for (final NetworkRequestInfo nri : nris) {
4617 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004618 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004619 for (final NetworkRequest req : nri.mRequests) {
4620 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004621 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004622 if (req.isListen()) {
4623 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4624 if (req.networkCapabilities.hasSignalStrength()
4625 && network.satisfiesImmutableCapabilitiesOf(req)) {
4626 updateSignalStrengthThresholds(network, "REGISTER", req);
4627 }
James Mattisf7027322020-12-13 16:28:14 -08004628 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004629 }
4630 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004631
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004632 // If this NRI has a satisfier already, it is replacing an older request that
4633 // has been removed. Track it.
4634 final NetworkRequest activeRequest = nri.getActiveRequest();
4635 if (null != activeRequest) {
4636 // If there is an active request, then for sure there is a satisfier.
4637 nri.getSatisfier().addRequest(activeRequest);
4638 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004639 }
James Mattisf7027322020-12-13 16:28:14 -08004640
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004641 if (mFlags.noRematchAllRequestsOnRegister()) {
4642 rematchNetworksAndRequests(nris);
4643 } else {
4644 rematchAllNetworksAndRequests();
4645 }
James Mattis45d81842021-01-10 14:24:24 -08004646
Chalard Jean0354d8c2021-01-12 10:58:56 +09004647 // Requests that have not been matched to a network will not have been sent to the
4648 // providers, because the old satisfier and the new satisfier are the same (null in this
4649 // case). Send these requests to the providers.
4650 for (final NetworkRequestInfo nri : nris) {
4651 for (final NetworkOfferInfo noi : mNetworkOffers) {
4652 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004653 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004654 }
4655 }
4656
James Mattisf7027322020-12-13 16:28:14 -08004657 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4658 final int callingUid) {
4659 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004660 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004661 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4662 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4663 handleReleaseNetworkRequest(
4664 nri.mRequests.get(0),
4665 callingUid,
4666 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004667 }
4668 }
4669
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004670 // Determines whether the network is the best (or could become the best, if it validated), for
4671 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4672 // on the value of reason:
4673 //
4674 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4675 // then it should be torn down.
4676 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4677 // then it should be lingered.
4678 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004679 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004680
Chalard Jean254bd162022-08-25 13:04:51 +09004681 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004682 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4683 return false;
4684 }
4685
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004686 final int numRequests;
4687 switch (reason) {
4688 case TEARDOWN:
4689 numRequests = nai.numRequestNetworkRequests();
4690 break;
4691 case LINGER:
4692 numRequests = nai.numForegroundNetworkRequests();
4693 break;
4694 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004695 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004696 return true;
4697 }
4698
Chalard Jean947acd42021-03-08 22:29:27 +09004699 if (numRequests > 0) return false;
4700
Paul Jensende49eb12015-06-25 15:30:08 -04004701 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004702 if (reason == UnneededFor.LINGER
4703 && !nri.isMultilayerRequest()
4704 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004705 // Background requests don't affect lingering.
4706 continue;
4707 }
4708
James Mattis3d229892020-11-16 16:46:28 -08004709 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004710 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004711 }
4712 }
Paul Jensende49eb12015-06-25 15:30:08 -04004713 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004714 }
4715
James Mattis3d229892020-11-16 16:46:28 -08004716 private boolean isNetworkPotentialSatisfier(
4717 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4718 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004719 // request, return immediately. For multilayer requests, check to see if any of the
4720 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004721 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4722 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004723 return false;
4724 }
4725 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004726 // This multilayer listen request is satisfied therefore no further requests need to be
4727 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004728 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004729 return false;
4730 }
James Mattis3d229892020-11-16 16:46:28 -08004731 // As non-multilayer listen requests have already returned, the below would only happen
4732 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004733 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004734 continue;
4735 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004736 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004737 // there is hope for it to become one if it validated, then it is needed.
4738 if (candidate.satisfies(req)) {
4739 // As soon as a network is found that satisfies a request, return. Specifically for
4740 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4741 // is important so as to not evaluate lower priority requests further in
4742 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004743 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4744 ? nri.getSatisfier() : null;
4745 // Note that this catches two important cases:
4746 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4747 // is currently satisfying the request. This is desirable when
4748 // cellular ends up validating but WiFi does not.
4749 // 2. Unvalidated WiFi will not be reaped when validated cellular
4750 // is currently satisfying the request. This is desirable when
4751 // WiFi ends up validating and out scoring cellular.
4752 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004753 }
4754 }
4755
4756 return false;
4757 }
4758
Erik Kline0c04b742016-07-07 16:50:58 +09004759 private NetworkRequestInfo getNriForAppRequest(
4760 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004761 // Looking up the app passed param request in mRequests isn't possible since it may return
4762 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4763 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004764 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4765 // to avoid potential race conditions when validating a package->uid mapping when sending
4766 // the callback on the very low-chance that an application shuts down prior to the callback
4767 // being sent.
4768 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4769 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004770
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004771 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004772 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004773 log(String.format("UID %d attempted to %s for unowned request %s",
4774 callingUid, requestedOperation, nri));
4775 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004776 }
Erik Kline0c04b742016-07-07 16:50:58 +09004777 }
4778
4779 return nri;
4780 }
4781
James Mattisf7027322020-12-13 16:28:14 -08004782 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4783 final String callingMethod) {
4784 if (nri.isMultilayerRequest()) {
4785 throw new IllegalStateException(
4786 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004787 }
4788 }
4789
James Mattisf7027322020-12-13 16:28:14 -08004790 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004791 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004792 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4793 // single NetworkRequest and thus does not apply to multilayer requests.
4794 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4795 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004796 return;
4797 }
James Mattis2516da32021-01-31 17:06:19 -08004798 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004799 return;
4800 }
James Mattisf7027322020-12-13 16:28:14 -08004801 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4802 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004803 }
4804 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004805 callCallbackForRequest(
4806 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004807 }
4808
James Mattisf7027322020-12-13 16:28:14 -08004809 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4810 final int callingUid,
4811 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004812 final NetworkRequestInfo nri =
4813 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4814 if (nri == null) {
4815 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004816 }
James Mattisf7027322020-12-13 16:28:14 -08004817 if (VDBG || (DBG && request.isRequest())) {
4818 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004819 }
4820 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004821 if (callOnUnavailable) {
4822 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4823 }
Erik Kline155a59a2015-11-25 12:49:38 +09004824 }
Erik Kline0c04b742016-07-07 16:50:58 +09004825
James Mattisa076c532020-12-02 14:12:41 -08004826 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004827 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004828 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004829 if (null == mNetworkRequests.remove(req)) {
4830 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4831 continue;
4832 }
James Mattisa076c532020-12-02 14:12:41 -08004833 if (req.isListen()) {
4834 removeListenRequestFromNetworks(req);
4835 }
4836 }
James Mattis8f036802021-06-20 16:26:01 -07004837 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004838 if (mDefaultNetworkRequests.remove(nri)) {
4839 // If this request was one of the defaults, then the UID rules need to be updated
4840 // WARNING : if the app(s) for which this network request is the default are doing
4841 // traffic, this will kill their connected sockets, even if an equivalent request
4842 // is going to be reinstated right away ; unconnected traffic will go on the default
4843 // until the new default is set, which will happen very soon.
4844 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4845 // remove ranges for those requests that won't have a replacement
4846 final NetworkAgentInfo satisfier = nri.getSatisfier();
4847 if (null != satisfier) {
4848 try {
paulhu0e79d952021-06-09 16:11:35 +08004849 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4850 satisfier.network.getNetId(),
4851 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004852 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004853 } catch (RemoteException e) {
4854 loge("Exception setting network preference default network", e);
4855 }
4856 }
4857 }
Junyu Lai35665cc2022-12-19 17:37:48 +08004858
Junyu Lai00d92df2022-07-05 11:01:52 +08004859 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004860 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004861 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004862
4863 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004864 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004865 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004866 }
4867 }
4868
Chalard Jean0354d8c2021-01-12 10:58:56 +09004869 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4870 // needed for this offer.
4871 for (final NetworkOfferInfo noi : mNetworkOffers) {
4872 for (final NetworkRequest req : nri.mRequests) {
4873 if (req.isRequest() && noi.offer.neededFor(req)) {
4874 noi.offer.onNetworkUnneeded(req);
4875 }
4876 }
4877 }
James Mattisa076c532020-12-02 14:12:41 -08004878 }
4879
James Mattis3ce3d3c2021-02-09 18:18:28 -08004880 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4881 for (final NetworkRequestInfo nri : nris) {
4882 if (mDefaultRequest == nri) {
4883 // Make sure we never remove the default request.
4884 continue;
4885 }
4886 handleRemoveNetworkRequest(nri);
4887 }
4888 }
4889
James Mattisa076c532020-12-02 14:12:41 -08004890 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4891 // listens don't have a singular affected Network. Check all networks to see
4892 // if this listen request applies and remove it.
4893 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4894 nai.removeRequest(req.requestId);
4895 if (req.networkCapabilities.hasSignalStrength()
4896 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4897 updateSignalStrengthThresholds(nai, "RELEASE", req);
4898 }
4899 }
4900 }
4901
4902 /**
4903 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4904 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4905 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4906 */
4907 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4908 boolean wasKept = false;
4909 final NetworkAgentInfo nai = nri.getSatisfier();
4910 if (nai != null) {
4911 final int requestLegacyType = nri.getActiveRequest().legacyType;
4912 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4913 nai.removeRequest(nri.getActiveRequest().requestId);
4914 if (VDBG || DDBG) {
4915 log(" Removing from current network " + nai.toShortString()
4916 + ", leaving " + nai.numNetworkRequests() + " requests.");
4917 }
4918 // If there are still lingered requests on this network, don't tear it down,
4919 // but resume lingering instead.
4920 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004921 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004922 notifyNetworkLosing(nai, now);
4923 }
4924 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4925 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4926 teardownUnneededNetwork(nai);
4927 } else {
4928 wasKept = true;
4929 }
James Mattisa076c532020-12-02 14:12:41 -08004930 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4931 // Went from foreground to background.
4932 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004933 }
4934
Erik Kline0c04b742016-07-07 16:50:58 +09004935 // Maintain the illusion. When this request arrived, we might have pretended
4936 // that a network connected to serve it, even though the network was already
4937 // connected. Now that this request has gone away, we might have to pretend
4938 // that the network disconnected. LegacyTypeTracker will generate that
4939 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004940 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004941 boolean doRemove = true;
4942 if (wasKept) {
4943 // check if any of the remaining requests for this network are for the
4944 // same legacy type - if so, don't remove the nai
4945 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4946 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004947 if (otherRequest.legacyType == requestLegacyType
4948 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004949 if (DBG) log(" still have other legacy request - leaving");
4950 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004951 }
4952 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004953 }
4954
Erik Kline0c04b742016-07-07 16:50:58 +09004955 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004956 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004957 }
4958 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004959 }
4960 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004961
Junyu Lai00d92df2022-07-05 11:01:52 +08004962 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004963 return checkAnyPermissionOf(
4964 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4965 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4966 }
4967
Lorenzo Colittid6459092016-07-04 12:55:44 +09004968 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004969 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004970 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004971 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004972 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004973 }
4974
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004975 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004976 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4977 enforceNetworkStackSettingsOrSetup();
4978 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4979 encodeBool(accept), encodeBool(always), network));
4980 }
4981
4982 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004983 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004984 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004985 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4986 }
4987
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004988 @Override
4989 public void setTestAllowBadWifiUntil(long timeMs) {
4990 enforceSettingsPermission();
4991 if (!Build.isDebuggable()) {
4992 throw new IllegalStateException("Does not support in non-debuggable build");
4993 }
4994
4995 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4996 throw new IllegalArgumentException("It should not exceed "
4997 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4998 }
4999
5000 mHandler.sendMessage(
5001 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5002 }
5003
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005004 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5005 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5006 " accept=" + accept + " always=" + always);
5007
5008 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5009 if (nai == null) {
5010 // Nothing to do.
5011 return;
5012 }
5013
Chalard Jean254bd162022-08-25 13:04:51 +09005014 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005015 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005016 return;
5017 }
5018
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005019 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005020 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005021 }
5022
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005023 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5024 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005025 // If network becomes partial connectivity and user already accepted to use this
5026 // network, we should respect the user's option and don't need to popup the
5027 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005028 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005029 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005030 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005031 }
5032
5033 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005034 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005035 }
5036
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005037 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005038 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005039 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005040 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005041 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005042 }
5043
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005044 }
5045
lucaslin2240ef62019-03-12 13:08:03 +08005046 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5047 boolean always) {
5048 if (DBG) {
5049 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5050 + " always=" + always);
5051 }
5052
5053 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5054 if (nai == null) {
5055 // Nothing to do.
5056 return;
5057 }
5058
Chalard Jean254bd162022-08-25 13:04:51 +09005059 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005060 // The network validated while the dialog box was up. Take no action.
5061 return;
5062 }
5063
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005064 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5065 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005066 }
5067
5068 // TODO: Use the current design or save the user choice into IpMemoryStore.
5069 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005070 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005071 }
5072
5073 if (!accept) {
5074 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005075 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005076 // Tear down the network.
5077 teardownUnneededNetwork(nai);
5078 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005079 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5080 // result in a partial connectivity result which will be processed by
5081 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005082 //
5083 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5084 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005085 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005086 }
5087 }
5088
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005089 private void handleSetAvoidUnvalidated(Network network) {
5090 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005091 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005092 // Nothing to do. The network either disconnected or revalidated.
5093 return;
5094 }
Chalard Jean254bd162022-08-25 13:04:51 +09005095 if (0L == nai.getAvoidUnvalidated()) {
5096 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005097 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005098 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005099 }
5100 }
5101
Chalard Jean5fb43c72022-09-08 19:03:14 +09005102 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005103 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005104 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005105 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09005106 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005107 }
5108
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005109 @Override
5110 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005111 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005112 mHandler.post(() -> {
5113 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5114 if (nai == null) return;
5115 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005116 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005117 });
5118 }
5119
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005120 /**
5121 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5122 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005123 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005124 * @param appExtras Bundle to use as intent extras for the captive portal application.
5125 * Must be treated as opaque to avoid preventing the captive portal app to
5126 * update its arguments.
5127 */
5128 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005129 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005130 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5131 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005132
5133 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5134 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005135 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5136 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005137 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5138
lucaslin75ff7022020-12-17 04:14:35 +08005139 final long token = Binder.clearCallingIdentity();
5140 try {
5141 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5142 } finally {
5143 Binder.restoreCallingIdentity(token);
5144 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005145 }
5146
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005147 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5148 private final Network mNetwork;
5149
5150 private CaptivePortalImpl(Network network) {
5151 mNetwork = network;
5152 }
5153
5154 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005155 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005156 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5157 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005158 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5159 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5160 // Since the network will be disconnected, skip notifying NetworkMonitor
5161 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005162 }
5163
Chiachang Wang938bfba2020-01-09 13:50:55 +08005164 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005165 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005166 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005167 }
5168
5169 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005170 public void appRequest(final int request) {
5171 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5172 if (nm == null) return;
5173
5174 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005175 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005176 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005177 }
5178 }
5179
5180 @Nullable
5181 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5182 // getNetworkAgentInfoForNetwork is thread-safe
5183 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5184 if (nai == null) return null;
5185
5186 // nai.networkMonitor() is thread-safe
5187 return nai.networkMonitor();
5188 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005189 }
5190
Hugo Benichic9048bc2016-09-14 23:23:08 +00005191 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005192 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005193 }
5194
Chalard Jean020b93a2022-09-01 13:20:14 +09005195 private boolean activelyPreferBadWifi() {
5196 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5197 }
5198
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005199 /**
5200 * Return whether the device should maintain continuous, working connectivity by switching away
5201 * from WiFi networks having no connectivity.
5202 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5203 */
5204 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005205 if (!checkNetworkStackPermission()) {
5206 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5207 }
5208 return avoidBadWifi();
5209 }
5210
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005211 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005212 ensureRunningOnConnectivityServiceThread();
5213 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005214 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005215 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005216 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005217 if (avoidBadWifi) {
5218 // If the device is now avoiding bad wifi, remove notifications that might have
5219 // been put up when the device didn't.
5220 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5221 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005222 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005223 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5224 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5225 for (final NetworkOfferInfo noi : offersToUpdate) {
5226 updateOfferScore(noi.offer);
5227 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005228 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005229 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005230 }
5231
Erik Kline95ecfee2016-10-02 18:02:14 +09005232 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005233 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005234 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005235 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005236 if (!configRestrict) {
5237 pw.println("Bad Wi-Fi avoidance: unrestricted");
5238 return;
5239 }
5240
5241 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5242 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005243 pw.println("Config restrict: " + configRestrict);
5244 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005245
Chalard Jeane0fdea32022-09-14 21:44:22 +09005246 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005247 String description;
5248 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005249 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005250 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005251 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005252 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005253 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005254 description = "avoid";
5255 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005256 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005257 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005258 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005259
5260 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5261 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005262 if (null == configValue) {
5263 description = "unset";
5264 } else if (configValue) {
5265 description = "force true";
5266 } else {
5267 description = "force false";
5268 }
5269 pw.println("Actively prefer bad wifi conf: " + description);
5270 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005271 pw.println("Network overrides:");
5272 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005273 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005274 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005275 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005276 }
5277 }
5278 pw.decreaseIndent();
5279 pw.decreaseIndent();
5280 }
5281
paulhu7746e4e2020-06-09 19:07:03 +08005282 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5283 // unify the method.
5284 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5285 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5286 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5287 return settingsComponent != null
5288 ? settingsComponent.getPackageName() : "com.android.settings";
5289 }
5290
lucaslinb1e8e382019-01-24 15:55:30 +08005291 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005292 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005293 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005294 switch (type) {
5295 case NO_INTERNET:
5296 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005297 // High priority because it is only displayed for explicitly selected networks.
5298 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005299 break;
lucasline117e2e2019-10-22 18:27:33 +08005300 case PRIVATE_DNS_BROKEN:
5301 action = Settings.ACTION_WIRELESS_SETTINGS;
5302 // High priority because we should let user know why there is no internet.
5303 highPriority = true;
5304 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005305 case LOST_INTERNET:
5306 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005307 // High priority because it could help the user avoid unexpected data usage.
5308 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005309 break;
lucaslin2240ef62019-03-12 13:08:03 +08005310 case PARTIAL_CONNECTIVITY:
5311 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005312 // Don't bother the user with a high-priority notification if the network was not
5313 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005314 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005315 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005316 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005317 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005318 return;
5319 }
5320
5321 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005322 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005323 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005324 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005325 // Some OEMs have their own Settings package. Thus, need to get the current using
5326 // Settings package name instead of just use default name "com.android.settings".
5327 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5328 intent.setClassName(settingsPkgName,
5329 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005330 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005331
paulhu2af50222020-10-11 22:52:27 +08005332 PendingIntent pendingIntent = PendingIntent.getActivity(
5333 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005334 0 /* requestCode */,
5335 intent,
paulhu2af50222020-10-11 22:52:27 +08005336 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005337
Serik Beketayevec8ad212020-12-07 22:43:07 -08005338 mNotifier.showNotification(
5339 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005340 }
5341
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005342 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5343 // Don't prompt if the network is validated, and don't prompt on captive portals
5344 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005345 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005346 return false;
5347 }
5348
5349 // If a network has partial connectivity, always prompt unless the user has already accepted
5350 // partial connectivity and selected don't ask again. This ensures that if the device
5351 // automatically connects to a network that has partial Internet access, the user will
5352 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005353 // because we have prompted them.
5354 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005355 return true;
5356 }
5357
5358 // If a network has no Internet access, only prompt if the network was explicitly selected
5359 // and if the user has not already told us to use the network regardless of whether it
5360 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005361 if (nai.networkAgentConfig.explicitlySelected
5362 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005363 return true;
5364 }
5365
5366 return false;
5367 }
5368
Chalard Jean5fb43c72022-09-08 19:03:14 +09005369 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5370 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005371
Chalard Jean5fb43c72022-09-08 19:03:14 +09005372 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5373 if (null == nai) return;
5374
5375 if (nai.setEvaluated()) {
5376 // If setEvaluated() returned true, the network never had any form of connectivity.
5377 // This may have an impact on request matching if bad WiFi avoidance is off and the
5378 // network was found not to have Internet access.
5379 nai.updateScoreForNetworkAgentUpdate();
5380 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005381
5382 // Also, if this is WiFi and it should be preferred actively, now is the time to
5383 // prompt the user that they walked past and connected to a bad WiFi.
5384 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5385 && !avoidBadWifi()
5386 && activelyPreferBadWifi()) {
5387 // The notification will be removed if the network validates or disconnects.
5388 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5389 return;
5390 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005391 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005392
Chalard Jean5fb43c72022-09-08 19:03:14 +09005393 if (!shouldPromptUnvalidated(nai)) return;
5394
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005395 // Stop automatically reconnecting to this network in the future. Automatically connecting
5396 // to a network that provides no or limited connectivity is not useful, because the user
5397 // cannot use that network except through the notification shown by this method, and the
5398 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005399 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005400
Chalard Jean254bd162022-08-25 13:04:51 +09005401 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005402 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005403 } else {
5404 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5405 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005406 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005407
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005408 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5409 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005410 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005411
lucaslin2240ef62019-03-12 13:08:03 +08005412 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5413 return;
5414 }
5415
5416 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005417 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005418 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005419 }
5420
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005421 @Override
5422 public int getMultipathPreference(Network network) {
5423 enforceAccessPermission();
5424
5425 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005426 if (nai != null && nai.networkCapabilities
5427 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005428 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5429 }
5430
Aaron Huang9a57acf2020-12-08 10:03:29 +08005431 final NetworkPolicyManager netPolicyManager =
5432 mContext.getSystemService(NetworkPolicyManager.class);
5433
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005434 final long token = Binder.clearCallingIdentity();
5435 final int networkPreference;
5436 try {
5437 networkPreference = netPolicyManager.getMultipathPreference(network);
5438 } finally {
5439 Binder.restoreCallingIdentity(token);
5440 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005441 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005442 return networkPreference;
5443 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005444 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5445 }
5446
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005447 @Override
5448 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005449 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005450 }
5451
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005452 private class InternalHandler extends Handler {
5453 public InternalHandler(Looper looper) {
5454 super(looper);
5455 }
5456
5457 @Override
5458 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005459 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005460 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005461 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005462 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005463 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005464 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005465 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005466 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005467 break;
5468 }
Jason Monka69f1b02013-10-10 14:02:51 -04005469 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005470 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5471 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005472 break;
5473 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005474 case EVENT_REGISTER_NETWORK_PROVIDER: {
5475 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005476 break;
5477 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005478 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5479 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005480 break;
5481 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005482 case EVENT_REGISTER_NETWORK_OFFER: {
5483 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5484 break;
5485 }
5486 case EVENT_UNREGISTER_NETWORK_OFFER: {
5487 final NetworkOfferInfo offer =
5488 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5489 if (null != offer) {
5490 handleUnregisterNetworkOffer(offer);
5491 }
5492 break;
5493 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005494 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005495 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5496 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5497 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005498 break;
5499 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005500 case EVENT_REGISTER_NETWORK_REQUEST:
5501 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005502 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005503 break;
5504 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005505 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5506 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005507 handleRegisterNetworkRequestWithIntent(msg);
5508 break;
5509 }
Erik Kline155a59a2015-11-25 12:49:38 +09005510 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5511 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5512 handleTimedOutNetworkRequest(nri);
5513 break;
5514 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005515 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5516 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5517 break;
5518 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005519 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005520 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5521 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005522 break;
5523 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005524 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005525 Network network = (Network) msg.obj;
5526 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005527 break;
5528 }
lucaslin2240ef62019-03-12 13:08:03 +08005529 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5530 Network network = (Network) msg.obj;
5531 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5532 toBool(msg.arg2));
5533 break;
5534 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005535 case EVENT_SET_AVOID_UNVALIDATED: {
5536 handleSetAvoidUnvalidated((Network) msg.obj);
5537 break;
5538 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005539 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5540 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005541 break;
5542 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005543 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5544 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005545 break;
5546 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005547 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005548 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005549 mKeepaliveTracker.handleStartKeepalive(msg);
5550 break;
5551 }
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005552 case NetworkAgent.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09005553 final AutomaticOnOffKeepalive ki =
5554 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
5555 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005556
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005557 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005558 boolean networkFound = false;
5559 final ArrayList<NetworkAgentInfo> vpnsRunningOnThisNetwork = new ArrayList<>();
5560 for (NetworkAgentInfo n : mNetworkAgentInfos) {
5561 if (n.network.equals(network)) networkFound = true;
5562 if (n.isVPN() && n.everConnected() && hasUnderlyingNetwork(n, network)) {
5563 vpnsRunningOnThisNetwork.add(n);
5564 }
5565 }
5566
5567 // If the network no longer exists, then the keepalive should have been
5568 // cleaned up already. There is no point trying to resume keepalives.
5569 if (!networkFound) return;
5570
5571 if (!vpnsRunningOnThisNetwork.isEmpty()) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005572 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005573 // TODO: check all the VPNs running on top of this network
5574 vpnsRunningOnThisNetwork.get(0).network.netId);
5575 } else {
5576 // If no VPN, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005577 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005578 }
5579 break;
5580 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005581 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005582 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005583 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
5584 (IBinder) msg.obj);
5585 if (ki == null) {
5586 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00005587 return;
5588 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005589 final int reason = msg.arg2;
5590 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005591 break;
5592 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005593 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5594 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5595 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005596 break;
5597 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005598 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5599 handlePrivateDnsSettingsChanged();
5600 break;
dalyk1720e542018-03-05 12:42:22 -05005601 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5602 handlePrivateDnsValidationUpdate(
5603 (PrivateDnsValidationUpdate) msg.obj);
5604 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005605 case EVENT_UID_BLOCKED_REASON_CHANGED:
5606 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005607 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005608 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5609 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5610 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005611 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005612 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5613 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005614 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005615 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005616 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005617 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005618 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5619 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005620 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005621 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005622 }
lucaslin1193a5d2021-01-21 02:04:15 +08005623 case EVENT_REPORT_NETWORK_ACTIVITY:
5624 mNetworkActivityTracker.handleReportNetworkActivity();
5625 break;
paulhu51f77dc2021-06-07 02:34:20 +00005626 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5627 handleMobileDataPreferredUidsChanged();
5628 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005629 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5630 final long timeMs = ((Long) msg.obj).longValue();
5631 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5632 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005633 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5634 handleIngressRateLimitChanged();
5635 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005636 case EVENT_USER_DOES_NOT_WANT:
5637 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5638 if (nai == null) break;
5639 nai.onPreventAutomaticReconnect();
5640 nai.disconnect();
5641 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00005642 case EVENT_SET_VPN_NETWORK_PREFERENCE:
5643 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
5644 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005645 }
5646 }
5647 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005648
Lorenzo Colittid6459092016-07-04 12:55:44 +09005649 @Override
markchien5776f962019-12-16 20:15:20 +08005650 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005651 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005652 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005653 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5654 Context.TETHERING_SERVICE);
5655 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005656 }
5657
Lorenzo Colittid6459092016-07-04 12:55:44 +09005658 @Override
markchien5776f962019-12-16 20:15:20 +08005659 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005660 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005661 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005662 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5663 Context.TETHERING_SERVICE);
5664 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005665 }
5666
Lorenzo Colittid6459092016-07-04 12:55:44 +09005667 @Override
markchien5776f962019-12-16 20:15:20 +08005668 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005669 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005670 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005671 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5672 Context.TETHERING_SERVICE);
5673 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005674 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005675
markchien5776f962019-12-16 20:15:20 +08005676
Lorenzo Colittid6459092016-07-04 12:55:44 +09005677 @Override
markchien5776f962019-12-16 20:15:20 +08005678 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005679 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005680 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005681 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5682 Context.TETHERING_SERVICE);
5683
5684 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005685 }
5686
Lorenzo Colittid6459092016-07-04 12:55:44 +09005687 @Override
markchien5776f962019-12-16 20:15:20 +08005688 @Deprecated
5689 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005690 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005691 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5692 Context.TETHERING_SERVICE);
5693
5694 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005695 }
5696
Udam Saini8f7d6a72017-06-07 12:06:28 -07005697 @Override
markchien5776f962019-12-16 20:15:20 +08005698 @Deprecated
5699 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005700 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005701 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5702 Context.TETHERING_SERVICE);
5703 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005704 }
5705
Robert Greenwalte0b00512014-07-02 09:59:16 -07005706 // Called when we lose the default network and have no replacement yet.
5707 // This will automatically be cleared after X seconds or a new default network
5708 // becomes CONNECTED, whichever happens first. The timer is started by the
5709 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005710 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005711 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005712 if (mNetTransitionWakeLock.isHeld()) {
5713 return;
5714 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005715 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005716 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5717 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005718 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005719 mWakelockLogs.log("ACQUIRE for " + forWhom);
5720 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005721 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005722 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005723 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005724 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005725
Hugo Benichi471b62a2017-03-30 23:18:10 +09005726 // Called when we gain a new default network to release the network transition wakelock in a
5727 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5728 // message is cancelled.
5729 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005730 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005731 if (!mNetTransitionWakeLock.isHeld()) {
5732 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005733 }
5734 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005735 // Cancel self timeout on wakelock hold.
5736 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5737 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5738 mHandler.sendMessageDelayed(msg, 1000);
5739 }
5740
5741 // Called when either message of ensureNetworkTransitionWakelock or
5742 // scheduleReleaseNetworkTransitionWakelock is processed.
5743 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5744 String event = eventName(eventId);
5745 synchronized (this) {
5746 if (!mNetTransitionWakeLock.isHeld()) {
5747 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005748 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005749 return;
5750 }
5751 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005752 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5753 mTotalWakelockDurationMs += lockDuration;
5754 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5755 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005756 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005757 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005758 }
5759
Robert Greenwalt986c7412010-09-08 15:24:47 -07005760 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005761 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005762 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005763 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005764 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005765 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005766 }
5767
Lorenzo Colittid6459092016-07-04 12:55:44 +09005768 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005769 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005770 enforceAccessPermission();
5771 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005772 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005773 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005774
5775 final NetworkAgentInfo nai;
5776 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005777 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005778 } else {
5779 nai = getNetworkAgentInfoForNetwork(network);
5780 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005781
5782 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005783 mHandler.obtainMessage(
5784 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005785 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005786
Hugo Benichid6b510a2017-04-06 17:22:18 +09005787 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005788 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005789 if (nai == null
5790 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005791 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005792 return;
5793 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005794 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005795 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005796 mConnectivityDiagnosticsHandler.sendMessage(
5797 mConnectivityDiagnosticsHandler.obtainMessage(
5798 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5799 new ReportedNetworkConnectivityInfo(
5800 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005801 return;
5802 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005803 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005804 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005805 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005806 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005807 // Validating a network that has not yet connected could result in a call to
5808 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005809 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005810 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005811 }
paulhu7aeba372020-12-30 00:42:19 +08005812 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5813 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005814 return;
5815 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005816
5817 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5818 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5819 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5820 // completed.
5821 mConnectivityDiagnosticsHandler.sendMessage(
5822 mConnectivityDiagnosticsHandler.obtainMessage(
5823 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5824 new ReportedNetworkConnectivityInfo(
5825 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005826 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005827 }
5828
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005829 // TODO: call into netd.
5830 private boolean queryUserAccess(int uid, Network network) {
5831 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5832 if (nai == null) return false;
5833
5834 // Any UID can use its default network.
5835 if (nai == getDefaultNetworkForUid(uid)) return true;
5836
5837 // Privileged apps can use any network.
5838 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5839 return true;
5840 }
5841
5842 // An unprivileged UID can use a VPN iff the VPN applies to it.
5843 if (nai.isVPN()) {
5844 return nai.networkCapabilities.appliesToUid(uid);
5845 }
5846
5847 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5848 // sockets, i.e., if it is the owner.
5849 final NetworkAgentInfo vpn = getVpnForUid(uid);
5850 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5851 && uid != vpn.networkCapabilities.getOwnerUid()) {
5852 return false;
5853 }
5854
5855 // The UID's permission must be at least sufficient for the network. Since the restricted
5856 // permission was already checked above, that just leaves background networks.
5857 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5858 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5859 }
5860
5861 // Unrestricted network. Anyone gets to use it.
5862 return true;
5863 }
5864
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005865 /**
5866 * Returns information about the proxy a certain network is using. If given a null network, it
5867 * it will return the proxy for the bound network for the caller app or the default proxy if
5868 * none.
5869 *
5870 * @param network the network we want to get the proxy information for.
5871 * @return Proxy information if a network has a proxy configured, or otherwise null.
5872 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005873 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005874 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005875 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005876 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005877 if (network == null) {
5878 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005879 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005880 true);
5881 if (activeNetwork == null) {
5882 return null;
5883 }
5884 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005885 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005886 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5887 // caller may not have.
5888 return getLinkPropertiesProxyInfo(network);
5889 }
5890 // No proxy info available if the calling UID does not have network access.
5891 return null;
5892 }
5893
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005894
5895 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005896 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5897 if (nai == null) return null;
5898 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005899 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5900 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005901 }
5902 }
5903
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005904 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005905 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005906 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005907 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005908 }
5909
Chalard Jean777e2e52018-06-07 18:02:37 +09005910 @Override
5911 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005912 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005913 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005914 }
5915
Junyu Lai970963e2022-10-25 15:46:47 +08005916 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005917 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005918 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005919 proxy = null;
5920 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005921 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005922 }
5923
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005924 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5925 // when any network changes proxy.
5926 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5927 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08005928 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
5929 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05005930 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5931
Chalard Jean7d97afc2018-06-07 17:41:29 +09005932 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005933 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005934 }
5935 }
5936
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005937 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005938 final private HashMap<Uri, Integer> mUriEventMap;
5939 final private Context mContext;
5940 final private Handler mHandler;
5941
5942 SettingsObserver(Context context, Handler handler) {
5943 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005944 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005945 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005946 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005947 }
5948
Erik Kline05f2b402015-04-30 12:58:40 +09005949 void observe(Uri uri, int what) {
5950 mUriEventMap.put(uri, what);
5951 final ContentResolver resolver = mContext.getContentResolver();
5952 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005953 }
5954
5955 @Override
5956 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005957 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005958 }
5959
5960 @Override
5961 public void onChange(boolean selfChange, Uri uri) {
5962 final Integer what = mUriEventMap.get(uri);
5963 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005964 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005965 } else {
5966 loge("No matching event to send for URI=" + uri);
5967 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005968 }
5969 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005970
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005971 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005972 Log.d(TAG, s);
5973 }
5974
5975 private static void logw(String s) {
5976 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005977 }
5978
Daniel Brightf9e945b2020-06-15 16:10:01 -07005979 private static void logwtf(String s) {
5980 Log.wtf(TAG, s);
5981 }
5982
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005983 private static void logwtf(String s, Throwable t) {
5984 Log.wtf(TAG, s, t);
5985 }
5986
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005987 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005988 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005989 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005990
Hugo Benichi39621362017-02-11 17:04:43 +09005991 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005992 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005993 }
5994
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005995 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005996 * Return the information of all ongoing VPNs.
5997 *
5998 * <p>This method is used to update NetworkStatsService.
5999 *
6000 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006001 */
junyulai2050bed2021-01-23 09:46:34 +08006002 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006003 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006004 if (mLockdownEnabled) {
6005 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006006 }
junyulai2050bed2021-01-23 09:46:34 +08006007 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006008 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006009 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006010 if (info != null) {
6011 infoList.add(info);
6012 }
6013 }
junyulai2050bed2021-01-23 09:46:34 +08006014 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006015 }
6016
6017 /**
6018 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006019 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006020 */
junyulai2050bed2021-01-23 09:46:34 +08006021 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006022 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006023 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6024 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006025 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6026 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6027 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006028 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6029 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006030 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006031 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006032 }
6033 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006034
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006035 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006036
6037 List<String> interfaces = new ArrayList<>();
6038 for (Network network : underlyingNetworks) {
6039 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6040 if (underlyingNai == null) continue;
6041 LinkProperties lp = underlyingNai.linkProperties;
6042 for (String iface : lp.getAllInterfaceNames()) {
6043 if (!TextUtils.isEmpty(iface)) {
6044 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006045 }
6046 }
Benedict Wong34857f82019-06-12 17:46:15 +00006047 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006048
6049 if (interfaces.isEmpty()) return null;
6050
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006051 // Must be non-null or NetworkStatsService will crash.
6052 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6053 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006054 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006055 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006056
junyulai2050bed2021-01-23 09:46:34 +08006057 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6058 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006059 }
6060
James Mattisd31bdfa2020-12-23 16:37:26 -08006061 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006062 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6063 Network[] underlyingNetworks) {
6064 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006065 if (underlyingNetworks == null && defaultNetwork != null) {
6066 // null underlying networks means to track the default.
6067 underlyingNetworks = new Network[] { defaultNetwork };
6068 }
6069 return underlyingNetworks;
6070 }
6071
6072 // Returns true iff |network| is an underlying network of |nai|.
6073 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6074 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6075 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006076 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006077 final Network[] underlying = underlyingNetworksOrDefault(
6078 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006079 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006080 }
6081
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006082 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006083 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006084 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006085 * When underlying networks change, such networks may have to update capabilities to reflect
6086 * things like the metered bit, their transports, and so on. The capabilities are calculated
6087 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006088 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006089 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006090 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006091 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006092 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006093 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006094 }
6095 }
6096 }
6097
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006098 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6099 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6100 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6101 // a VPN is not up.
6102 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6103 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6104 for (UidRange range : blockedUidRanges) {
6105 if (range.contains(uid)) return true;
6106 }
6107 return false;
6108 }
6109
6110 @Override
6111 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006112 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006113 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6114 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6115 }
6116
6117 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6118 if (DBG) {
6119 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6120 + Arrays.toString(ranges));
6121 }
6122 // Cannot use a Set since the list of UID ranges might contain duplicates.
6123 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6124 for (int i = 0; i < ranges.length; i++) {
6125 if (requireVpn) {
6126 newVpnBlockedUidRanges.add(ranges[i]);
6127 } else {
6128 newVpnBlockedUidRanges.remove(ranges[i]);
6129 }
6130 }
6131
6132 try {
6133 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6134 } catch (RemoteException | ServiceSpecificException e) {
6135 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6136 + Arrays.toString(ranges) + "): netd command failed: " + e);
6137 }
6138
Motomu Utsumib08654c2022-05-11 05:56:26 +00006139 if (SdkLevel.isAtLeastT()) {
6140 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6141 }
6142
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006143 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6144 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006145 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6146 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006147 }
6148
6149 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6150 }
6151
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006152 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006153 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006154 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006155 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006156 }
6157
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006158 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6159 return mLockdownEnabled
6160 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6161 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006162 }
6163
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006164 private NetworkAgentInfo getLegacyLockdownNai() {
6165 if (!mLockdownEnabled) {
6166 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006167 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006168 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006169 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6170 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006171
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006172 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006173 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6174 // a local variable. There is no need to make a copy because its contents cannot change.
6175 final Network[] underlying = nai.declaredUnderlyingNetworks;
6176 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006177 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006178 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006179
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006180 // The legacy lockdown VPN always uses the default network.
6181 // If the VPN's underlying network is no longer the current default network, it means that
6182 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006183 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6184 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006185 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006186 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006187 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006188 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006189
6190 return nai;
6191 };
6192
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006193 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6194 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6195 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006196 private DetailedState getLegacyLockdownState(DetailedState origState) {
6197 if (origState != DetailedState.CONNECTED) {
6198 return origState;
6199 }
6200 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6201 ? DetailedState.CONNECTING
6202 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006203 }
6204
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006205 private void filterForLegacyLockdown(NetworkInfo ni) {
6206 if (!mLockdownEnabled || !ni.isConnected()) return;
6207 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6208 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6209 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6210 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6211 // network, this time with a state of CONNECTED.
6212 //
6213 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6214 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6215 // is not too far off the truth, since an always-on VPN, when not connected, is always
6216 // trying to reconnect.
6217 if (getLegacyLockdownNai() == null) {
6218 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6219 }
6220 }
6221
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006222 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006223 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006224 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006225 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006226 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6227 return;
6228 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006229 final long ident = Binder.clearCallingIdentity();
6230 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006231 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006232 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006233 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006234 } finally {
6235 Binder.restoreCallingIdentity(ident);
6236 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006237 }
Wink Savillecb117d32013-08-29 14:57:08 -07006238
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006239 @Override
6240 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006241 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006242 final long ident = Binder.clearCallingIdentity();
6243 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006244 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006245 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006246 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6247 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006248 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006249 } finally {
6250 Binder.restoreCallingIdentity(ident);
6251 }
6252 }
6253
James Mattis02220e22021-03-13 19:27:21 -08006254 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006255 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6256 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6257 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006258 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006259 }
6260
James Mattis02220e22021-03-13 19:27:21 -08006261 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006262 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006263 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006264 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6265 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006266 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006267 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6268 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6269 }
junyulaid91e7052020-08-28 13:44:33 +08006270 }
6271
James Mattis02220e22021-03-13 19:27:21 -08006272 private void onPackageChanged(@NonNull final String packageName) {
6273 // This is necessary in case a package is added or removed, but also when it's replaced to
6274 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6275 // as one in the preferences, then it should follow the same routing as that other package,
6276 // which means updating the rules is never to be needed in this case (whether it joins or
6277 // leaves a UID with a preference).
6278 if (isMappedInOemNetworkPreference(packageName)) {
6279 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6280 }
6281 }
6282
6283 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006284 @Override
6285 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006286 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006287 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006288 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006289
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006290 // User should be filled for below intents, check the existence.
6291 if (user == null) {
6292 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6293 return;
6294 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006295
Lorenzo Colitticd675292021-02-04 17:32:07 +09006296 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006297 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006298 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006299 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006300 } else {
junyulaid91e7052020-08-28 13:44:33 +08006301 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006302 }
6303 }
6304 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006305
James Mattis02220e22021-03-13 19:27:21 -08006306 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6307 @Override
6308 public void onReceive(Context context, Intent intent) {
6309 ensureRunningOnConnectivityServiceThread();
6310 switch (intent.getAction()) {
6311 case Intent.ACTION_PACKAGE_ADDED:
6312 case Intent.ACTION_PACKAGE_REMOVED:
6313 case Intent.ACTION_PACKAGE_REPLACED:
6314 onPackageChanged(intent.getData().getSchemeSpecificPart());
6315 break;
6316 default:
6317 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6318 }
6319 }
6320 };
6321
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006322 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006323 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006324
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006325 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006326 public final String name;
6327 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006328 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006329 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006330
lifraf3a3492021-03-10 13:58:14 +08006331 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6332 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006333 this.name = name;
6334 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006335 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006336 mDeathRecipient = deathRecipient;
6337
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006338 if (mDeathRecipient == null) {
6339 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006340 }
6341 }
6342
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006343 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006344 try {
6345 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6346 } catch (RemoteException e) {
6347 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006348 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006349 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006350 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006351
James Mattis4fce5d12020-11-12 15:53:42 -08006352 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6353 for (int i = 0; i < requests.size(); i++) {
6354 ensureNetworkRequestHasType(requests.get(i));
6355 }
6356 }
6357
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006358 private void ensureNetworkRequestHasType(NetworkRequest request) {
6359 if (request.type == NetworkRequest.Type.NONE) {
6360 throw new IllegalArgumentException(
6361 "All NetworkRequests in ConnectivityService must have a type");
6362 }
6363 }
6364
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006365 /**
6366 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006367 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006368 */
James Mattis258ea3c2020-11-15 15:04:40 -08006369 @VisibleForTesting
6370 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006371 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6372 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006373 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006374
James Mattisa076c532020-12-02 14:12:41 -08006375 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6376 void setSatisfier(
6377 @Nullable final NetworkAgentInfo satisfier,
6378 @Nullable final NetworkRequest activeRequest) {
6379 mSatisfier = satisfier;
6380 mActiveRequest = activeRequest;
6381 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006382
James Mattisd31bdfa2020-12-23 16:37:26 -08006383 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006384 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006385 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006386 private NetworkAgentInfo mSatisfier;
6387 NetworkAgentInfo getSatisfier() {
6388 return mSatisfier;
6389 }
6390
6391 // The request in mRequests assigned to a network agent. This is null if none of the
6392 // requests in mRequests can be satisfied. This member has the constraint of only being
6393 // accessible on the handler thread.
6394 @Nullable
6395 private NetworkRequest mActiveRequest;
6396 NetworkRequest getActiveRequest() {
6397 return mActiveRequest;
6398 }
6399
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006400 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006401 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006402 @Nullable
6403 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006404
6405 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006406 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006407 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006408 final int mPid;
6409 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006410 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006411 @Nullable
6412 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006413
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006414 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006415 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006416
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006417 // Effective UID of this request. This is different from mUid when a privileged process
6418 // files a request on behalf of another UID. This UID is used to determine blocked status,
6419 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6420 // maximum limit of registered callbacks per UID.
6421 final int mAsUid;
6422
paulhu48291862021-07-14 14:53:57 +08006423 // Preference order of this request.
6424 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006425
James Mattis3ce3d3c2021-02-09 18:18:28 -08006426 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6427 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6428 // maintained for keying off of. This is only a concern when the original nri
6429 // mNetworkRequests changes which happens currently for apps that register callbacks to
6430 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6431 // that match the per-app default nri that currently tracks the calling app's uid so that
6432 // callbacks are fired at the appropriate time. When the callbacks fire,
6433 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6434 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6435 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6436 @NonNull
6437 private final NetworkRequest mNetworkRequestForCallback;
6438 NetworkRequest getNetworkRequestForCallback() {
6439 return mNetworkRequestForCallback;
6440 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006441
James Mattisd31bdfa2020-12-23 16:37:26 -08006442 /**
6443 * Get the list of UIDs this nri applies to.
6444 */
6445 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006446 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006447 // networkCapabilities.getUids() returns a defensive copy.
6448 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006449 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6450 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006451 }
6452
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006453 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6454 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006455 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006456 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006457 }
6458
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006459 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006460 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006461 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006462 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006463 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006464 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006465 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006466 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006467 mBinder = null;
6468 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006469 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006470 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006471 mPerUidCounter = getRequestCounter(this);
6472 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006473 /**
6474 * Location sensitive data not included in pending intent. Only included in
6475 * {@link NetworkCallback}.
6476 */
6477 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006478 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006479 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006480 }
6481
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006482 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006483 @Nullable final IBinder binder,
6484 @NetworkCallback.Flag int callbackFlags,
6485 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006486 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6487 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006488 }
6489
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006490 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006491 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006492 @Nullable final IBinder binder,
6493 @NetworkCallback.Flag int callbackFlags,
6494 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006495 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006496 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006497 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006498 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006499 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006500 mBinder = binder;
6501 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006502 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006503 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006504 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006505 mPerUidCounter = getRequestCounter(this);
6506 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006507 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006508 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006509 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006510 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006511 }
6512
James Mattis3ce3d3c2021-02-09 18:18:28 -08006513 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6514 @NonNull final List<NetworkRequest> r) {
6515 super();
6516 ensureAllNetworkRequestsHaveType(r);
6517 mRequests = initializeRequests(r);
6518 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006519 final NetworkAgentInfo satisfier = nri.getSatisfier();
6520 if (null != satisfier) {
6521 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6522 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006523 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006524 // As this code creates a new NRI with a new set of requests, figure out which of
6525 // the list of requests should be the active request. It is always the first
6526 // request of the list that can be satisfied by the satisfier since the order of
6527 // requests is a priority order.
6528 // Note even in the presence of a satisfier there may not be an active request,
6529 // when the satisfier is the no-service network.
6530 NetworkRequest activeRequest = null;
6531 for (final NetworkRequest candidate : r) {
6532 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6533 activeRequest = candidate;
6534 break;
6535 }
6536 }
6537 setSatisfier(satisfier, activeRequest);
6538 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006539 mMessenger = nri.mMessenger;
6540 mBinder = nri.mBinder;
6541 mPid = nri.mPid;
6542 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006543 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006544 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006545 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006546 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006547 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006548 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006549 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006550 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006551 }
6552
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006553 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006554 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006555 }
6556
paulhue9913722021-05-26 15:19:20 +08006557 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006558 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006559 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006560 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006561 }
6562
James Mattis2516da32021-01-31 17:06:19 -08006563 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6564 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6565 // false.
6566 boolean isBeingSatisfied() {
6567 return (null != mSatisfier && null != mActiveRequest);
6568 }
6569
James Mattis3d229892020-11-16 16:46:28 -08006570 boolean isMultilayerRequest() {
6571 return mRequests.size() > 1;
6572 }
6573
James Mattis45d81842021-01-10 14:24:24 -08006574 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6575 // Creating a defensive copy to prevent the sender from modifying the list being
6576 // reflected in the return value of this method.
6577 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006578 return Collections.unmodifiableList(tempRequests);
6579 }
6580
James Mattisb1392002021-03-31 13:57:52 -07006581 void linkDeathRecipient() {
6582 if (null != mBinder) {
6583 try {
6584 mBinder.linkToDeath(this, 0);
6585 } catch (RemoteException e) {
6586 binderDied();
6587 }
6588 }
6589 }
6590
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006591 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006592 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006593 try {
6594 mBinder.unlinkToDeath(this, 0);
6595 } catch (NoSuchElementException e) {
6596 // Temporary workaround for b/194394697 pending analysis of additional logs
6597 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6598 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006599 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006600 }
6601
paulhu48291862021-07-14 14:53:57 +08006602 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6603 // Compare two preference orders.
6604 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006605 }
6606
paulhu48291862021-07-14 14:53:57 +08006607 int getPreferenceOrderForNetd() {
6608 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6609 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6610 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006611 }
paulhu48291862021-07-14 14:53:57 +08006612 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006613 }
6614
James Mattis4fce5d12020-11-12 15:53:42 -08006615 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006616 public void binderDied() {
6617 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006618 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006619 // As an immutable collection, mRequests cannot change by the time the
6620 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6621 // is acceptable. Use handleReleaseNetworkRequest and not directly
6622 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6623 // the app already unregistered the request.
6624 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6625 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006626 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006627
James Mattis4fce5d12020-11-12 15:53:42 -08006628 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006629 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006630 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6631 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006632 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006633 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006634 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006635 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006636 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006637 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006638 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006639 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006640 }
6641
Junyu Lai00d92df2022-07-05 11:01:52 +08006642 // Keep backward compatibility since the ServiceSpecificException is used by
6643 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6644 public static class RequestInfoPerUidCounter extends PerUidCounter {
6645 RequestInfoPerUidCounter(int maxCountPerUid) {
6646 super(maxCountPerUid);
6647 }
6648
6649 @Override
6650 public synchronized void incrementCountOrThrow(int uid) {
6651 try {
6652 super.incrementCountOrThrow(uid);
6653 } catch (IllegalStateException e) {
6654 throw new ServiceSpecificException(
6655 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6656 "Uid " + uid + " exceeded its allotted requests limit");
6657 }
6658 }
6659
6660 @Override
6661 public synchronized void decrementCountOrThrow(int uid) {
6662 throw new UnsupportedOperationException("Use decrementCount instead.");
6663 }
6664
6665 public synchronized void decrementCount(int uid) {
6666 try {
6667 super.decrementCountOrThrow(uid);
6668 } catch (IllegalStateException e) {
6669 logwtf("Exception when decrement per uid request count: ", e);
6670 }
6671 }
6672 }
6673
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006674 // This checks that the passed capabilities either do not request a
6675 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006676 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006677 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006678 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006679 throw new SecurityException("Insufficient permissions to request a specific SSID");
6680 }
paulhu1a407652019-03-22 16:35:06 +08006681
6682 if (nc.hasSignalStrength()
6683 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6684 throw new SecurityException(
6685 "Insufficient permissions to request a specific signal strength");
6686 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006687 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006688
junyulai2217bec2021-04-14 23:33:31 +08006689 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006690 enforceNetworkFactoryPermission();
6691 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006692 }
6693
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006694 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006695 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006696 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006697 // mNetworkRequests may contain the same value multiple times in case of
6698 // multilayer requests. It won't matter in this case because the thresholds
6699 // will then be the same and be deduplicated as they enter the `thresholds` set.
6700 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006701 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6702 for (final NetworkRequest req : nri.mRequests) {
6703 if (req.networkCapabilities.hasSignalStrength()
6704 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6705 thresholds.add(req.networkCapabilities.getSignalStrength());
6706 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006707 }
6708 }
6709 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006710 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006711 }
6712
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006713 private void updateSignalStrengthThresholds(
6714 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006715 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006716
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006717 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006718 String detail;
6719 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6720 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6721 } else {
6722 detail = reason;
6723 }
6724 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006725 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006726 }
6727
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006728 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006729 }
6730
Chalard Jeandd421992021-12-16 23:16:02 +09006731 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006732 if (nc == null) {
6733 return;
6734 }
6735 NetworkSpecifier ns = nc.getNetworkSpecifier();
6736 if (ns == null) {
6737 return;
6738 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006739 if (ns instanceof MatchAllNetworkSpecifier) {
6740 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6741 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006742 }
6743
Chalard Jeandd421992021-12-16 23:16:02 +09006744 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006745 ensureValidNetworkSpecifier(nc);
6746 if (nc.isPrivateDnsBroken()) {
6747 throw new IllegalArgumentException("Can't request broken private DNS");
6748 }
Chalard Jeande665262022-02-25 16:12:12 +09006749 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006750 throw new IllegalArgumentException("Can't request access UIDs");
6751 }
lucasline117e2e2019-10-22 18:27:33 +08006752 }
6753
Chalard Jeandd421992021-12-16 23:16:02 +09006754 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6755 ensureListenableCapabilities(nc);
6756 final String badCapability = nc.describeFirstNonRequestableCapability();
6757 if (badCapability != null) {
6758 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6759 }
6760 }
6761
Chiachang Wang3bc52762021-11-25 14:17:57 +08006762 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6763 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006764 private boolean isTargetSdkAtleast(int version, int callingUid,
6765 @NonNull String callingPackageName) {
6766 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006767 final PackageManager pm =
6768 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006769 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006770 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006771 if (callingVersion < version) return false;
6772 } catch (PackageManager.NameNotFoundException e) { }
6773 return true;
6774 }
6775
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006776 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006777 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006778 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006779 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006780 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006781 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006782 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6783 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006784 throw new SecurityException("Insufficient permissions to specify legacy type");
6785 }
markchienfac84a22020-03-18 21:16:15 +08006786 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006787 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006788 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006789 // Privileged callers can track the default network of another UID by passing in a UID.
6790 if (asUid != Process.INVALID_UID) {
6791 enforceSettingsPermission();
6792 } else {
6793 asUid = callingUid;
6794 }
junyulaiad010792021-01-11 16:53:38 +08006795 final NetworkRequest.Type reqType;
6796 try {
6797 reqType = NetworkRequest.Type.values()[reqTypeInt];
6798 } catch (ArrayIndexOutOfBoundsException e) {
6799 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6800 }
6801 switch (reqType) {
6802 case TRACK_DEFAULT:
6803 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006804 // is unused and will be replaced by ones appropriate for the UID (usually, the
6805 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006806 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006807 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006808 enforceAccessPermission();
6809 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006810 case TRACK_SYSTEM_DEFAULT:
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08006811 enforceSettingsOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006812 networkCapabilities = new NetworkCapabilities(defaultNc);
6813 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006814 case BACKGROUND_REQUEST:
6815 enforceNetworkStackOrSettingsPermission();
6816 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006817 case REQUEST:
6818 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6819 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006820 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006821 // TODO: this is incorrect. We mark the request as metered or not depending on
6822 // the state of the app when the request is filed, but we never change the
6823 // request if the app changes network state. http://b/29964605
6824 enforceMeteredApnPolicy(networkCapabilities);
6825 break;
junyulai1b1c8742021-03-12 20:05:08 +08006826 case LISTEN_FOR_BEST:
6827 enforceAccessPermission();
6828 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6829 break;
junyulaiad010792021-01-11 16:53:38 +08006830 default:
6831 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006832 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006833 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006834 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006835 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006836
junyulai1b1c8742021-03-12 20:05:08 +08006837 // Enforce FOREGROUND if the caller does not have permission to use background network.
6838 if (reqType == LISTEN_FOR_BEST) {
6839 restrictBackgroundRequestForCaller(networkCapabilities);
6840 }
6841
6842 // Set the UID range for this request to the single UID of the requester, unless the
6843 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006844 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6845 // are no visible methods to set the UIDs, an app could use reflection to try and get
6846 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006847 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006848 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6849 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006850
Etan Cohen85000162017-02-05 10:42:27 -08006851 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006852 throw new IllegalArgumentException("Bad timeout specified");
6853 }
Etan Cohen9786d922015-11-18 10:56:15 -08006854
James Mattis3ce3d3c2021-02-09 18:18:28 -08006855 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006856 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006857 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006858 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006859 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006860 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006861
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006862 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6863 // copied from the default request above. (This is necessary to ensure, for example, that
6864 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6865 // changes don't alter request matching.
6866 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6867 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006868 throw new IllegalStateException(
6869 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006870 + networkCapabilities + " vs. " + defaultNc);
6871 }
6872
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006873 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006874 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006875 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006876 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006877 }
6878 return networkRequest;
6879 }
6880
James Mattis3ce3d3c2021-02-09 18:18:28 -08006881 /**
6882 * Return the nri to be used when registering a network request. Specifically, this is used with
6883 * requests registered to track the default request. If there is currently a per-app default
6884 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6885 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006886 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6887 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006888 * @param nr the network request for the nri.
6889 * @param msgr the messenger for the nri.
6890 * @param binder the binder for the nri.
6891 * @param callingAttributionTag the calling attribution tag for the nri.
6892 * @return the nri to register.
6893 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006894 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006895 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006896 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006897 @Nullable String callingAttributionTag) {
6898 final List<NetworkRequest> requests;
6899 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6900 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006901 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006902 } else {
6903 requests = Collections.singletonList(nr);
6904 }
Roshan Pius951c0032020-12-22 15:10:42 -08006905 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006906 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006907 }
6908
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006909 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006910 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006911 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006912 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6913 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6914 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6915 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006916 }
junyulai96bd9fe2022-03-08 17:36:42 +08006917 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006918 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006919 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006920 }
6921 }
6922
fenglu3f357402015-03-20 11:29:56 -07006923 @Override
fenglub00f4882015-04-21 17:12:05 -07006924 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006925 enforceAccessPermission();
6926 NetworkAgentInfo nai = null;
6927 if (network == null) {
6928 return false;
6929 }
6930 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006931 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006932 }
6933 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006934 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006935 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006936 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006937 Integer uidReqs = mBandwidthRequests.get(uid);
6938 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006939 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006940 }
6941 mBandwidthRequests.put(uid, ++uidReqs);
6942 }
fenglu3f357402015-03-20 11:29:56 -07006943 return true;
6944 }
6945 return false;
6946 }
6947
Felipe Leme0a5ae422016-06-20 16:36:29 -07006948 private boolean isSystem(int uid) {
6949 return uid < Process.FIRST_APPLICATION_UID;
6950 }
fenglu3f357402015-03-20 11:29:56 -07006951
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006952 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006953 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006954 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006955 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006956 return;
6957 }
Hugo Benichi39621362017-02-11 17:04:43 +09006958 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6959 // Policy already enforced.
6960 return;
6961 }
paulhuaf50d7d2020-12-24 19:47:34 +08006962 final long ident = Binder.clearCallingIdentity();
6963 try {
6964 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6965 // If UID is restricted, don't allow them to bring up metered APNs.
6966 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6967 }
6968 } finally {
6969 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006970 }
6971 }
6972
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006973 @Override
6974 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006975 PendingIntent operation, @NonNull String callingPackageName,
6976 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006977 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006978 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006979 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006980 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006981 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006982 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006983 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006984 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006985 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006986 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6987 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006988
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006989 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006990 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006991 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6992 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006993 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006994 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6995 nri));
6996 return networkRequest;
6997 }
6998
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006999 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7000 mHandler.sendMessageDelayed(
7001 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007002 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007003 }
7004
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007005 @Override
7006 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007007 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007008 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007009 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007010 }
7011
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007012 // In order to implement the compatibility measure for pre-M apps that call
7013 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7014 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7015 // This ensures it has permission to do so.
7016 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7017 if (nc == null) {
7018 return false;
7019 }
7020 int[] transportTypes = nc.getTransportTypes();
7021 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7022 return false;
7023 }
7024 try {
7025 mContext.enforceCallingOrSelfPermission(
7026 android.Manifest.permission.ACCESS_WIFI_STATE,
7027 "ConnectivityService");
7028 } catch (SecurityException e) {
7029 return false;
7030 }
7031 return true;
7032 }
7033
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007034 @Override
7035 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007036 Messenger messenger, IBinder binder,
7037 @NetworkCallback.Flag int callbackFlags,
7038 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007039 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007040 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7041 enforceAccessPermission();
7042 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007043
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007044 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007045 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007046 Binder.getCallingPid(), callingUid, callingPackageName);
7047 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007048 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7049 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7050 // onLost and onAvailable callbacks when networks move in and out of the background.
7051 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7052 // can't request networks.
7053 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007054 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007055
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007056 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007057 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007058 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007059 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007060 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007061 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007062
7063 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7064 return networkRequest;
7065 }
7066
7067 @Override
7068 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007069 PendingIntent operation, @NonNull String callingPackageName,
7070 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007071 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007072 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007073 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7074 enforceAccessPermission();
7075 }
Chalard Jeandd421992021-12-16 23:16:02 +09007076 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007077 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007078 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007079 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007080 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007081
7082 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007083 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007084 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7085 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007086 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007087
WeiZhang1cc3f172021-06-03 19:02:04 -05007088 mHandler.sendMessage(mHandler.obtainMessage(
7089 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007090 }
7091
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007092 /** Returns the next Network provider ID. */
7093 public final int nextNetworkProviderId() {
7094 return mNextNetworkProviderId.getAndIncrement();
7095 }
7096
Erik Kline0c04b742016-07-07 16:50:58 +09007097 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007098 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007099 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007100 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007101 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007102 }
7103
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007104 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7105 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007106 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7107 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7108 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007109 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007110 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007111 return;
7112 }
7113
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007114 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7115 mNetworkProviderInfos.put(npi.messenger, npi);
7116 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007117 }
7118
7119 @Override
7120 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007121 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007122 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007123 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007124 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007125 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7126 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007127 }
7128
7129 @Override
7130 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007131 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007132 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007133 }
7134
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007135 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007136 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007137 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7138 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007139 Objects.requireNonNull(score);
7140 Objects.requireNonNull(caps);
7141 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007142 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007143 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007144 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7145 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007146 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7147 }
7148
Chalard Jeanbb902a52021-08-18 01:35:19 +09007149 private void updateOfferScore(final NetworkOffer offer) {
7150 final boolean yieldToBadWiFi =
7151 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7152 final NetworkOffer newOffer = new NetworkOffer(
7153 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7154 offer.caps, offer.callback, offer.providerId);
7155 if (offer.equals(newOffer)) return;
7156 handleRegisterNetworkOffer(newOffer);
7157 }
7158
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007159 @Override
7160 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007161 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007162 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7163 }
7164
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007165 private void handleUnregisterNetworkProvider(Messenger messenger) {
7166 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7167 if (npi == null) {
7168 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007169 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007170 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007171 // Unregister all the offers from this provider
7172 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7173 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007174 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007175 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7176 toRemove.add(noi);
7177 }
7178 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007179 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007180 handleUnregisterNetworkOffer(noi);
7181 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007182 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007183 }
7184
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007185 @Override
James Mattisf7027322020-12-13 16:28:14 -08007186 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007187 if (request.hasTransport(TRANSPORT_TEST)) {
7188 enforceNetworkFactoryOrTestNetworksPermission();
7189 } else {
7190 enforceNetworkFactoryPermission();
7191 }
James Mattisf7027322020-12-13 16:28:14 -08007192 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7193 if (nri != null) {
7194 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7195 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7196 mHandler.post(() -> handleReleaseNetworkRequest(
7197 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7198 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007199 }
7200
Paul Jensen1f567382015-02-13 14:18:39 -05007201 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7202 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007203 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007204 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007205 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007206 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007207 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007208
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007209 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007210 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007211 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007212
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007213 // UID ranges for users that are currently blocked by VPNs.
7214 // This array is accessed and iterated on multiple threads without holding locks, so its
7215 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7216 // (on the handler thread).
7217 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7218
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007219 // Must only be accessed on the handler thread
7220 @NonNull
7221 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7222
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007223 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007224 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007225
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007226 // Current OEM network preferences. This object must only be written to on the handler thread.
7227 // Since it is immutable and always non-null, other threads may read it if they only care
7228 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007229 @NonNull
7230 private OemNetworkPreferences mOemNetworkPreferences =
7231 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007232 // Current per-profile network preferences. This object follows the same threading rules as
7233 // the OEM network preferences above.
7234 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007235 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7236 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007237
lucaslin3ba7cc22022-12-19 02:35:33 +00007238 // Current VPN network preferences. This object follows the same threading rules as the OEM
7239 // network preferences above.
7240 @NonNull
7241 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7242 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7243
paulhu51f77dc2021-06-07 02:34:20 +00007244 // A set of UIDs that should use mobile data preferentially if available. This object follows
7245 // the same threading rules as the OEM network preferences above.
7246 @NonNull
7247 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7248
James Mattiscb1e0362021-04-06 17:07:42 -07007249 // OemNetworkPreferences activity String log entries.
7250 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7251 @NonNull
7252 private final LocalLog mOemNetworkPreferencesLogs =
7253 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7254
James Mattis02220e22021-03-13 19:27:21 -08007255 /**
7256 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7257 * @param packageName the package name to check existence of a mapping for.
7258 * @return true if a mapping exists, false otherwise
7259 */
7260 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7261 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7262 }
7263
James Mattise3ef1912020-12-20 11:09:58 -08007264 // The always-on request for an Internet-capable network that apps without a specific default
7265 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007266 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007267 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007268 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007269 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007270 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007271 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007272 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007273
James Mattisd31bdfa2020-12-23 16:37:26 -08007274 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7275 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7276 }
7277
7278 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007279 * Return the default network request currently tracking the given uid.
7280 * @param uid the uid to check.
7281 * @return the NetworkRequestInfo tracking the given uid.
7282 */
7283 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007284 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007285 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007286 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007287 // Checking the first request is sufficient as only multilayer requests will have more
7288 // than one request and for multilayer, all requests will track the same uids.
7289 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007290 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007291 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007292 highestPriorityNri = nri;
7293 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007294 }
7295 }
paulhuaa0743d2021-05-26 21:56:03 +08007296 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007297 }
7298
7299 /**
7300 * Get a copy of the network requests of the default request that is currently tracking the
7301 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007302 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7303 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007304 * @param requestorUid the uid to check the default for.
7305 * @param requestorPackageName the requestor's package name.
7306 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7307 */
7308 @NonNull
7309 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007310 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007311 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007312 getDefaultRequestTrackingUid(asUid).mRequests,
7313 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007314 }
7315
7316 /**
7317 * Copy the given nri's NetworkRequest collection.
7318 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007319 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7320 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007321 * @param requestorUid the uid to set on the copied collection.
7322 * @param requestorPackageName the package name to set on the copied collection.
7323 * @return the copied NetworkRequest collection.
7324 */
7325 @NonNull
7326 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007327 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7328 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007329 final List<NetworkRequest> requests = new ArrayList<>();
7330 for (final NetworkRequest nr : requestsToCopy) {
7331 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007332 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007333 nr.legacyType, nextNetworkRequestId(), nr.type));
7334 }
7335 return requests;
7336 }
7337
7338 @NonNull
7339 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007340 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7341 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007342 // These capabilities are for a TRACK_DEFAULT callback, so:
7343 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7344 // mDefaultRequest and a per-UID default request.
7345 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007346 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007347 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007348 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7349 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007350 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007351 restrictRequestUidsForCallerAndSetRequestorInfo(
7352 netCap, requestorUid, requestorPackageName);
7353 return netCap;
7354 }
7355
7356 /**
7357 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7358 * @param nr the network request to check for equality against.
7359 * @return the nri if one exists, null otherwise.
7360 */
7361 @Nullable
7362 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7363 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7364 if (nri.getNetworkRequestForCallback().equals(nr)) {
7365 return nri;
7366 }
7367 }
7368 return null;
7369 }
7370
7371 /**
7372 * Check if an nri is currently being managed by per-app default networking.
7373 * @param nri the nri to check.
7374 * @return true if this nri is currently being managed by per-app default networking.
7375 */
7376 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7377 // nri.mRequests.get(0) is only different from the original request filed in
7378 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7379 // functionality therefore if these two don't match, it means this particular nri is
7380 // currently being managed by a per-app default.
7381 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7382 }
7383
7384 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007385 * Determine if an nri is a managed default request that disallows default networking.
7386 * @param nri the request to evaluate
7387 * @return true if device-default networking is disallowed
7388 */
7389 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7390 // Check if this nri is a managed default that supports the default network at its
7391 // lowest priority request.
7392 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7393 final NetworkCapabilities lowestPriorityNetCap =
7394 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7395 return isPerAppDefaultRequest(nri)
7396 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7397 lowestPriorityNetCap));
7398 }
7399
Erik Kline05f2b402015-04-30 12:58:40 +09007400 // Request used to optionally keep mobile data active even when higher
7401 // priority networks like Wi-Fi are active.
7402 private final NetworkRequest mDefaultMobileDataRequest;
7403
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007404 // Request used to optionally keep wifi data active even when higher
7405 // priority networks like ethernet are active.
7406 private final NetworkRequest mDefaultWifiRequest;
7407
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007408 // Request used to optionally keep vehicle internal network always active
7409 private final NetworkRequest mDefaultVehicleRequest;
7410
James Mattisd31bdfa2020-12-23 16:37:26 -08007411 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7412 // network with no service. This NAI should never be matched against, nor should any public API
7413 // ever return the associated network. For this reason, this NAI is not in the list of available
7414 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7415 // default requests that don't support using the device default network which will ultimately
7416 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7417 @VisibleForTesting
7418 final NetworkAgentInfo mNoServiceNetwork;
7419
Chalard Jean5b409c72021-02-04 13:12:59 +09007420 // The NetworkAgentInfo currently satisfying the default request, if any.
7421 private NetworkAgentInfo getDefaultNetwork() {
7422 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007423 }
7424
James Mattis2516da32021-01-31 17:06:19 -08007425 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007426 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007427 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7428 // Currently, all network requests will have the same uids therefore checking the first
7429 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007430 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007431 if (null == uids) {
7432 continue;
7433 }
7434 for (final UidRange range : uids) {
7435 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007436 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007437 highestPriorityNri = nri;
7438 }
James Mattis2516da32021-01-31 17:06:19 -08007439 }
7440 }
7441 }
paulhuaa0743d2021-05-26 21:56:03 +08007442 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007443 }
7444
Varun Ananddf569952019-02-06 10:13:38 -08007445 @Nullable
7446 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7447 return nai != null ? nai.network : null;
7448 }
7449
7450 private void ensureRunningOnConnectivityServiceThread() {
7451 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7452 throw new IllegalStateException(
7453 "Not running on ConnectivityService thread: "
7454 + Thread.currentThread().getName());
7455 }
7456 }
7457
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007458 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007459 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7460 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007461 }
7462
Chalard Jean29d06db2018-05-02 21:14:54 +09007463 /**
7464 * Register a new agent with ConnectivityService to handle a network.
7465 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007466 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007467 * @param networkInfo the initial info associated with this network. It can be updated later :
7468 * see {@link #updateNetworkInfo}.
7469 * @param linkProperties the initial link properties of this network. They can be updated
7470 * later : see {@link #updateLinkProperties}.
7471 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007472 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007473 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007474 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007475 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007476 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007477 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007478 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007479 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007480 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7481 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007482 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7483 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7484 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007485 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007486 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007487 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007488 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007489 } else {
7490 enforceNetworkFactoryPermission();
7491 }
7492
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007493 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007494 final long token = Binder.clearCallingIdentity();
7495 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007496 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007497 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007498 } finally {
7499 Binder.restoreCallingIdentity(token);
7500 }
7501 }
7502
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007503 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007504 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007505 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7506 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007507
Chalard Jeandbc46952022-02-02 00:14:18 +09007508 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7509 // and mutate them at any time.
7510 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7511 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7512 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7513
Chalard Jean366c5252022-01-25 18:27:53 +09007514 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007515 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007516 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7517 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007518 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007519 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007520 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007521 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7522 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007523
Chalard Jeandbc46952022-02-02 00:14:18 +09007524 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007525 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007526 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007527 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007528 mDeps.getNetworkStack().makeNetworkMonitor(
7529 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007530 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7531 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007532 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007533 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007534 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007535 }
7536
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007537 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007538 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007539 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007540 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007541 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007542 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7543 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7544 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007545
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007546 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007547
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007548 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007549 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007550 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007551 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007552
7553 try {
7554 networkMonitor.start();
7555 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007556 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007557 }
Chalard Jean366c5252022-01-25 18:27:53 +09007558
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007559 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007560 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007561 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007562 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007563 }
7564
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007565 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7566 @NonNull public final NetworkOffer offer;
7567
7568 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7569 this.offer = offer;
7570 }
7571
7572 @Override
7573 public void binderDied() {
7574 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7575 }
7576 }
7577
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007578 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7579 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7580 if (npi.providerId == providerId) return true;
7581 }
7582 return false;
7583 }
7584
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007585 /**
7586 * Register or update a network offer.
7587 * @param newOffer The new offer. If the callback member is the same as an existing
7588 * offer, it is an update of that offer.
7589 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007590 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007591 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7592 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007593 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007594 // This may actually happen if a provider updates its score or registers and then
7595 // immediately unregisters. The offer would still be in the handler queue, but the
7596 // provider would have been removed.
7597 if (DBG) log("Received offer from an unregistered provider");
7598 return;
7599 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007600 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7601 if (null != existingOffer) {
7602 handleUnregisterNetworkOffer(existingOffer);
7603 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007604 if (DBG) {
7605 // handleUnregisterNetworkOffer has already logged the old offer
7606 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7607 }
7608 } else {
7609 if (DBG) {
7610 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7611 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007612 }
7613 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7614 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007615 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007616 } catch (RemoteException e) {
7617 noi.binderDied();
7618 return;
7619 }
7620 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007621 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007622 }
7623
7624 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7625 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007626 if (DBG) {
7627 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7628 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007629
7630 // If the provider removes the offer and dies immediately afterwards this
7631 // function may be called twice in a row, but the array will no longer contain
7632 // the offer.
7633 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007634 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007635 }
7636
7637 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7638 @NonNull final INetworkOfferCallback callback) {
7639 ensureRunningOnConnectivityServiceThread();
7640 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007641 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007642 }
7643 return null;
7644 }
7645
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007646 /**
7647 * Called when receiving LinkProperties directly from a NetworkAgent.
7648 * Stores into |nai| any data coming from the agent that might also be written to the network's
7649 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7650 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007651 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007652 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007653 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7654 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007655 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007656 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007657 }
7658
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007659 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007660 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007661 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007662
Lorenzo Colittid523d142020-04-01 20:16:30 +09007663 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7664 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7665 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007666 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007667
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007668 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007669
7670 // update filtering rules, need to happen after the interface update so netd knows about the
7671 // new interface (the interface name -> index map becomes initialized)
7672 updateVpnFiltering(newLp, oldLp, networkAgent);
7673
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007674 updateMtu(newLp, oldLp);
7675 // TODO - figure out what to do for clat
7676// for (LinkProperties lp : newLp.getStackedLinks()) {
7677// updateMtu(lp, null);
7678// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007679 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007680 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7681 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007682
Erik Klineb9888902016-04-05 13:30:49 +09007683 updateRoutes(newLp, oldLp, netId);
7684 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007685 // Make sure LinkProperties represents the latest private DNS status.
7686 // This does not need to be done before updateDnses because the
7687 // LinkProperties are not the source of the private DNS configuration.
7688 // updateDnses will fetch the private DNS configuration from DnsManager.
7689 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007690
Chalard Jean5b409c72021-02-04 13:12:59 +09007691 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007692 handleApplyDefaultProxy(newLp.getHttpProxy());
7693 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007694 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007695 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007696
7697 updateWakeOnLan(newLp);
7698
Hai Shalome58bdc62021-01-11 18:45:34 -08007699 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7700 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7701 // does, it needs to be merged here.
7702 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7703 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007704
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007705 // TODO - move this check to cover the whole function
7706 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007707 synchronized (networkAgent) {
7708 networkAgent.linkProperties = newLp;
7709 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007710 // Start or stop DNS64 detection and 464xlat according to network state.
7711 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007712 // Notify NSS when relevant events happened. Currently, NSS only cares about
7713 // interface changed to update clat interfaces accounting.
7714 final boolean interfacesChanged = oldLp == null
7715 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7716 if (interfacesChanged) {
7717 notifyIfacesChangedForNetworkStats();
7718 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007719 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7720 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007721 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007722 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007723
7724 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007725 }
7726
Hai Shalome58bdc62021-01-11 18:45:34 -08007727 /**
7728 * @param naData captive portal data from NetworkAgent
7729 * @param apiData captive portal data from capport API
7730 */
7731 @Nullable
7732 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7733 CaptivePortalData apiData) {
7734 if (naData == null || apiData == null) {
7735 return naData == null ? apiData : naData;
7736 }
7737 final CaptivePortalData.Builder captivePortalBuilder =
7738 new CaptivePortalData.Builder(naData);
7739
7740 if (apiData.isCaptive()) {
7741 captivePortalBuilder.setCaptive(true);
7742 }
7743 if (apiData.isSessionExtendable()) {
7744 captivePortalBuilder.setSessionExtendable(true);
7745 }
7746 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7747 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7748 // otherwise data would be inconsistent. Prefer the capport API info if present,
7749 // as it can generally be refreshed more often.
7750 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7751 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7752 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7753 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7754 // No source has time / bytes remaining information: surface the newest refresh time
7755 // for other fields
7756 captivePortalBuilder.setRefreshTime(
7757 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7758 }
7759
Hai Shalom7c6ab402021-02-04 19:34:06 -08007760 // Prioritize the user portal URL from the network agent if the source is authenticated.
7761 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7762 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7763 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7764 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007765 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007766 // Prioritize the venue information URL from the network agent if the source is
7767 // authenticated.
7768 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7769 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7770 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7771 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007772 }
7773 return captivePortalBuilder.build();
7774 }
7775
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007776 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007777 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007778 // marks on unsupported interfaces is harmless.
7779 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7780 return;
7781 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007782
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007783 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7784 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7785
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007786 // Mask/mark of zero will not detect anything interesting.
7787 // Don't install rules unless both values are nonzero.
7788 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007789 return;
7790 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007791
7792 final String prefix = "iface:" + iface;
7793 try {
7794 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007795 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007796 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007797 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007798 }
7799 } catch (Exception e) {
7800 loge("Exception modifying wakeup packet monitoring: " + e);
7801 }
7802
Joel Scherpelza235a812017-05-22 13:47:41 +09007803 }
7804
Junyu Lai970963e2022-10-25 15:46:47 +08007805 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09007806 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007807 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007808 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08007809 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09007810 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007811 for (final String iface : interfaceDiff.added) {
7812 try {
7813 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007814 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007815 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007816 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7817 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007818 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007819 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007820 }
Paul Jensenbff73492014-04-28 10:33:11 -04007821 }
7822 }
Chalard Jean9589e722019-11-19 19:03:53 +09007823 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007824 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007825 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007826 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007827 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007828 } catch (Exception e) {
7829 loge("Exception removing interface: " + e);
7830 }
7831 }
7832 }
7833
Tyler Weare4314862019-12-05 14:55:30 -08007834 // TODO: move to frameworks/libs/net.
7835 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7836 final String nextHop;
7837
7838 switch (route.getType()) {
7839 case RouteInfo.RTN_UNICAST:
7840 if (route.hasGateway()) {
7841 nextHop = route.getGateway().getHostAddress();
7842 } else {
7843 nextHop = INetd.NEXTHOP_NONE;
7844 }
7845 break;
7846 case RouteInfo.RTN_UNREACHABLE:
7847 nextHop = INetd.NEXTHOP_UNREACHABLE;
7848 break;
7849 case RouteInfo.RTN_THROW:
7850 nextHop = INetd.NEXTHOP_THROW;
7851 break;
7852 default:
7853 nextHop = INetd.NEXTHOP_NONE;
7854 break;
7855 }
7856
7857 final RouteInfoParcel rip = new RouteInfoParcel();
7858 rip.ifName = route.getInterface();
7859 rip.destination = route.getDestination().toString();
7860 rip.nextHop = nextHop;
7861 rip.mtu = route.getMtu();
7862
7863 return rip;
7864 }
7865
Paul Jensene0fd4a82014-08-06 15:51:33 -04007866 /**
7867 * Have netd update routes from oldLp to newLp.
7868 * @return true if routes changed between oldLp and newLp
7869 */
Junyu Lai970963e2022-10-25 15:46:47 +08007870 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7871 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007872 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007873 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7874 new CompareOrUpdateResult<>(
7875 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08007876 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08007877 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007878
7879 // add routes before removing old in case it helps with continuous connectivity
7880
Chalard Jean9dd11612018-06-04 16:52:49 +09007881 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007882 for (RouteInfo route : routeDiff.added) {
7883 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007884 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007885 try {
Tyler Weare4314862019-12-05 14:55:30 -08007886 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007887 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007888 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007889 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007890 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007891 }
7892 }
7893 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007894 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007895 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007896 try {
Tyler Weare4314862019-12-05 14:55:30 -08007897 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007898 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007899 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007900 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007901 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007902 }
7903 }
7904
7905 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007906 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007907 try {
Tyler Weare4314862019-12-05 14:55:30 -08007908 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007909 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007910 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007911 }
7912 }
Tyler Weare4314862019-12-05 14:55:30 -08007913
7914 for (RouteInfo route : routeDiff.updated) {
7915 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7916 try {
7917 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7918 } catch (Exception e) {
7919 loge("Exception in networkUpdateRouteParcel: " + e);
7920 }
7921 }
7922 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7923 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007924 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007925
Junyu Lai970963e2022-10-25 15:46:47 +08007926 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7927 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09007928 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7929 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007930 }
Erik Klineb9888902016-04-05 13:30:49 +09007931
Erik Kline31b4a9e2018-01-11 21:07:29 +09007932 if (DBG) {
7933 final Collection<InetAddress> dnses = newLp.getDnsServers();
7934 log("Setting DNS servers for network " + netId + " to " + dnses);
7935 }
Erik Klineb9888902016-04-05 13:30:49 +09007936 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007937 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007938 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007939 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007940 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007941 }
Erik Kline54e35c02017-04-07 15:29:29 +09007942 }
7943
Junyu Lai970963e2022-10-25 15:46:47 +08007944 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7945 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007946 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7947 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007948 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7949 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007950
7951 if (!wasFiltering && !needsFiltering) {
7952 // Nothing to do.
7953 return;
7954 }
7955
7956 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7957 // Nothing changed.
7958 return;
7959 }
7960
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007961 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007962 if (ranges == null || ranges.isEmpty()) {
7963 return;
7964 }
7965
Qingxi Libb8da982020-01-17 17:54:27 -08007966 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007967 // TODO: this create a window of opportunity for apps to receive traffic between the time
7968 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007969 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007970 // old rules are being removed.
7971 if (wasFiltering) {
7972 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7973 }
7974 if (needsFiltering) {
7975 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7976 }
7977 }
7978
Valentin Iftime9fa35092019-09-24 13:32:13 +02007979 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007980 if (mWolSupportedInterfaces == null) {
7981 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007982 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007983 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007984 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7985 }
7986
Luke Huangb913c812018-08-24 20:33:16 +08007987 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007988 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007989 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007990 }
7991 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007992 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007993 }
Luke Huangb913c812018-08-24 20:33:16 +08007994 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007995 }
7996
Chalard Jean62edfd82019-12-02 18:39:29 +09007997 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7998 @NonNull final NetworkCapabilities newNc) {
7999 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8000 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008001 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008002 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008003 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008004 } catch (RemoteException | ServiceSpecificException e) {
8005 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008006 }
8007 }
8008 }
8009
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008010 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008011 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008012 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008013 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008014 underlyingNetworks = underlyingNetworksOrDefault(
8015 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008016 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008017 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8018 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008019 // metered if any underlying is metered, or originally declared metered by the agent.
8020 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008021 boolean roaming = false; // roaming if any underlying is roaming
8022 boolean congested = false; // congested if any underlying is congested
8023 boolean suspended = true; // suspended if all underlying are suspended
8024
8025 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008026 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008027 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008028 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008029 for (Network underlyingNetwork : underlyingNetworks) {
8030 final NetworkAgentInfo underlying =
8031 getNetworkAgentInfoForNetwork(underlyingNetwork);
8032 if (underlying == null) continue;
8033
8034 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8035 hadUnderlyingNetworks = true;
8036 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008037 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008038 }
8039
8040 // Merge capabilities of this underlying network. For bandwidth, assume the
8041 // worst case.
8042 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8043 underlyingCaps.getLinkDownstreamBandwidthKbps());
8044 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8045 underlyingCaps.getLinkUpstreamBandwidthKbps());
8046 // If this underlying network is metered, the VPN is metered (it may cost money
8047 // to send packets on this network).
8048 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8049 // If this underlying network is roaming, the VPN is roaming (the billing structure
8050 // is different than the usual, local one).
8051 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8052 // If this underlying network is congested, the VPN is congested (the current
8053 // condition of the network affects the performance of this network).
8054 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8055 // If this network is not suspended, the VPN is not suspended (the VPN
8056 // is able to transfer some data).
8057 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008058 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008059 }
8060 }
8061 if (!hadUnderlyingNetworks) {
8062 // No idea what the underlying networks are; assume reasonable defaults
8063 metered = true;
8064 roaming = false;
8065 congested = false;
8066 suspended = false;
8067 }
8068
Chalard Jean1d420b32022-10-12 16:39:37 +09008069 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008070 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8071 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8072 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8073 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8074 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8075 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008076 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008077 }
8078
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008079 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008080 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8081 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8082 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008083 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008084 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008085 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008086 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008087 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8088 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008089 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008090 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008091 if (nai.everConnected()
8092 && !nai.isVPN()
8093 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008094 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008095 // does not cause any request (that is not a listen) currently matching that agent to
8096 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008097 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008098 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008099 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008100 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008101 }
8102
Paul Jensen53f08952015-06-16 14:27:36 -04008103 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008104 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008105 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008106 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008107 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008108 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008109 }
Chalard Jean254bd162022-08-25 13:04:51 +09008110 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008111 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008112 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008113 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008114 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008115 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008116 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008117 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008118 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008119 }
Chalard Jean254bd162022-08-25 13:04:51 +09008120 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008121 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8122 } else {
8123 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8124 }
lucasline117e2e2019-10-22 18:27:33 +08008125 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008126
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008127 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008128 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8129 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008130 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008131 }
8132
Lorenzo Colittibd079452021-07-02 11:47:57 +09008133 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008134 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008135 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008136 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008137 }
8138
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008139 return newNc;
8140 }
8141
Lorenzo Colitti44840702021-01-11 22:27:57 +09008142 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8143 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8144 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8145 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8146 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8147 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8148 if (prevSuspended != suspended) {
8149 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8150 // onResumed have been removed.
8151 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8152 : ConnectivityManager.CALLBACK_RESUMED);
8153 }
8154 if (prevSuspended != suspended || prevRoaming != roaming) {
8155 // updateNetworkInfo will mix in the suspended info from the capabilities and
8156 // take appropriate action for the network having possibly changed state.
8157 updateNetworkInfo(nai, nai.networkInfo);
8158 }
8159 }
8160
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008161 /**
8162 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8163 *
8164 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8165 * capabilities we manage and store in {@code nai}, such as validated status and captive
8166 * portal status)
8167 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8168 * potentially triggers rematches.
8169 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8170 * change.)
8171 *
8172 * @param oldScore score of the network before any of the changes that prompted us
8173 * to call this function.
8174 * @param nai the network having its capabilities updated.
8175 * @param nc the new network capabilities.
8176 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008177 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008178 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008179 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008180 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008181 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8182 if (null != differences) {
8183 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8184 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008185 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008186 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008187
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008188 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008189 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008190 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008191
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008192 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008193 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8194 // the change we're processing can't affect any requests, it can only affect the listens
8195 // on this network. We might have been called by rematchNetworkAndRequests when a
8196 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008197 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008198 } else {
8199 // If the requestable capabilities have changed or the score changed, we can't have been
8200 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008201 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008202 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008203 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008204 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008205
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008206 final boolean oldMetered = prevNc.isMetered();
8207 final boolean newMetered = newNc.isMetered();
8208 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008209
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008210 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008211 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8212 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008213 }
junyulaif2c67e42018-08-07 19:50:45 +08008214
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008215 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8216 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008217
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008218 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008219 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008220 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008221 }
8222
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008223 // This network might have been underlying another network. Propagate its capabilities.
8224 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008225
8226 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008227 mDnsManager.updateTransportsForNetwork(
8228 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008229 }
lucaslin53e8a262021-06-08 01:43:59 +08008230
8231 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008232 }
8233
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008234 /** Convenience method to update the capabilities for a given network. */
8235 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008236 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008237 }
8238
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008239 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008240 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008241 *
8242 * Ingress interface filtering enforces that all apps under the given network can only receive
8243 * packets from the network's interface (and loopback). This is important for VPNs because
8244 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8245 * non-VPN interfaces.
8246 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008247 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008248 * 1. the network is an app VPN (not legacy VPN)
8249 * 2. the VPN does not allow bypass
8250 * 3. the VPN is fully-routed
8251 * 4. the VPN interface is non-null
8252 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008253 * @see INetd#firewallAddUidInterfaceRules
8254 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008255 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008256 @Nullable
8257 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008258 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008259 if (nc == null || lp == null) return null;
8260 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008261 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008262 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008263 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008264 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008265 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008266 && !lp.hasExcludeRoute()) {
8267 return lp.getInterfaceName();
8268 }
8269 return null;
8270 }
8271
8272 /**
8273 * Returns whether we need to set interface filtering rule or not
8274 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008275 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008276 String isolationIface) {
8277 // Allow rules are always needed if VPN isolation is enabled.
8278 if (isolationIface != null) return true;
8279
8280 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8281 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8282 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8283 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008284 }
8285
Chiachang Wang28afaff2020-12-10 22:24:47 +08008286 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8287 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8288 int index = 0;
8289 for (UidRange range : ranges) {
8290 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8291 index++;
8292 }
8293 return stableRanges;
8294 }
8295
Chalard Jeane6c95272022-01-25 21:04:21 +09008296 private static UidRangeParcel[] intsToUidRangeStableParcels(
8297 final @NonNull ArraySet<Integer> uids) {
8298 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8299 int index = 0;
8300 for (int uid : uids) {
8301 stableRanges[index] = new UidRangeParcel(uid, uid);
8302 index++;
8303 }
8304 return stableRanges;
8305 }
8306
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008307 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8308 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8309 for (int i = 0; i < ranges.length; i++) {
8310 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8311 }
8312 return stableRanges;
8313 }
8314
Ken Chen5e65a852020-12-24 12:59:10 +08008315 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8316 int[] exemptUids) {
8317 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8318 try {
8319 mNetd.socketDestroy(ranges, exemptUids);
8320 } catch (Exception e) {
8321 loge("Exception in socket destroy: ", e);
8322 }
8323 }
8324 }
8325
paulhuaa0743d2021-05-26 21:56:03 +08008326 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008327 int[] exemptUids = new int[2];
8328 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8329 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8330 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8331 exemptUids[0] = VPN_UID;
8332 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8333 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8334
8335 maybeCloseSockets(nai, ranges, exemptUids);
8336 try {
8337 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008338 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008339 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008340 } else {
paulhu0e79d952021-06-09 16:11:35 +08008341 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008342 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008343 }
8344 } catch (Exception e) {
8345 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8346 " on netId " + nai.network.netId + ". " + e);
8347 }
8348 maybeCloseSockets(nai, ranges, exemptUids);
8349 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008350
lucaslin53e8a262021-06-08 01:43:59 +08008351 private boolean isProxySetOnAnyDefaultNetwork() {
8352 ensureRunningOnConnectivityServiceThread();
8353 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8354 final NetworkAgentInfo nai = nri.getSatisfier();
8355 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8356 return true;
8357 }
8358 }
8359 return false;
8360 }
8361
8362 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8363 NetworkCapabilities newNc) {
8364 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8365 // the proxy might be changed since the default network satisfied by the apps might also
8366 // changed.
8367 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8368 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008369 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8370 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008371 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008372 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8373 mProxyTracker.sendProxyBroadcast();
8374 }
8375 }
8376
Chalard Jeane6c95272022-01-25 21:04:21 +09008377 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8378 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008379 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8380 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008381 if (null == prevRanges) prevRanges = new ArraySet<>();
8382 if (null == newRanges) newRanges = new ArraySet<>();
8383 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8384
8385 prevRanges.removeAll(newRanges);
8386 newRanges.removeAll(prevRangesCopy);
8387
8388 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008389 // When updating the VPN uid routing rules, add the new range first then remove the old
8390 // range. If old range were removed first, there would be a window between the old
8391 // range being removed and the new range being added, during which UIDs contained
8392 // in both ranges are not subject to any VPN routing rules. Adding new range before
8393 // removing old range works because, unlike the filtering rules below, it's possible to
8394 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008395 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8396 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8397 // [1-5] & [1-2],[4-5] == [3]
8398 // Then we can do:
8399 // maybeCloseSockets([3])
8400 // mNetd.networkAddUidRanges([1-2],[4-5])
8401 // mNetd.networkRemoveUidRanges([1-5])
8402 // maybeCloseSockets([3])
8403 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8404 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008405 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008406 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008407 }
8408 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008409 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008410 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008411 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8412 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008413 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8414 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008415 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008416 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008417 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8418 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8419 // were added first and then newRanges got removed later, there would be only one uid
8420 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8421 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8422 // Note that this is in contrast with the (more robust) update of VPN routing rules
8423 // above, where the addition of new ranges happens before the removal of old ranges.
8424 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8425 // to be removed will never overlap with the new range to be added.
8426 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008427 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8428 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008429 }
8430 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008431 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008432 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008433 } catch (Exception e) {
8434 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008435 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008436 }
8437 }
8438
Chalard Jeande665262022-02-25 16:12:12 +09008439 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008440 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8441 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008442 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8443 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008444 if (prevEmpty && newEmpty) return;
8445
8446 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008447 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008448 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008449 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008450
8451 if (prevUids.equals(newUids)) return;
8452
8453 // This implementation is very simple and vastly faster for sets of Integers than
8454 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8455 // a key computed from the value and has storage for that.
8456 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8457 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8458 toRemove.removeAll(newUids);
8459 toAdd.removeAll(prevUids);
8460
8461 try {
8462 if (!toAdd.isEmpty()) {
8463 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8464 nai.network.netId,
8465 intsToUidRangeStableParcels(toAdd),
8466 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8467 }
8468 if (!toRemove.isEmpty()) {
8469 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8470 nai.network.netId,
8471 intsToUidRangeStableParcels(toRemove),
8472 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8473 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008474 } catch (ServiceSpecificException e) {
8475 // Has the interface disappeared since the network was built ?
8476 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008477 } catch (RemoteException e) {
8478 // Netd died. This usually causes a runtime restart anyway.
8479 }
8480 }
8481
Junyu Lai2ed7d412022-10-07 16:52:21 +08008482 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8483 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008484 ensureRunningOnConnectivityServiceThread();
8485
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008486 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008487 // Ignore updates for disconnected networks
8488 return;
8489 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008490 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008491 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008492 + "; created=" + nai.getCreatedTime()
8493 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008494 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008495 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8496 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008497 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008498 }
8499
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008500 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8501 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008502 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008503 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008504 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008505 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8506 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8507 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008508 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8509 // need to be sent as a separate extra.
8510 final NetworkRequest req = nri.isMultilayerRequest()
8511 ? nri.getActiveRequest()
8512 // Non-multilayer listen requests do not have an active request
8513 : nri.mRequests.get(0);
8514 if (req == null) {
8515 Log.wtf(TAG, "No request in NRI " + nri);
8516 }
8517 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008518 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008519 sendIntent(nri.mPendingIntent, intent);
8520 }
8521 // else not handled
8522 }
8523
Michael Groover73f69482023-01-27 11:01:25 -06008524 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
8525 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008526 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8527 mPendingIntentWakeLock.acquire();
8528 try {
8529 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008530 final BroadcastOptions options = BroadcastOptions.makeBasic();
8531 if (SdkLevel.isAtLeastT()) {
8532 // Explicitly disallow the receiver from starting activities, to prevent apps from
8533 // utilizing the PendingIntent as a backdoor to do this.
8534 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8535 }
8536 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8537 null /* requiredPermission */,
8538 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008539 } catch (PendingIntent.CanceledException e) {
8540 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8541 mPendingIntentWakeLock.release();
8542 releasePendingNetworkRequest(pendingIntent);
8543 }
8544 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8545 }
8546
8547 @Override
8548 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8549 String resultData, Bundle resultExtras) {
8550 if (DBG) log("Finished sending " + pendingIntent);
8551 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008552 // Release with a delay so the receiving client has an opportunity to put in its
8553 // own request.
8554 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008555 }
8556
Chalard Jean46bfbf02022-02-02 00:56:25 +09008557 // networkAgent is only allowed to be null if notificationType is
8558 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8559 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008560 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008561 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008562 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008563 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008564 // Default request has no msgr. Also prevents callbacks from being invoked for
8565 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8566 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8567 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008568 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008569 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008570 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008571 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008572 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008573 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008574 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008575 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8576 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008577 }
Roshan Pius951c0032020-12-22 15:10:42 -08008578 final boolean includeLocationSensitiveInfo =
8579 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008580 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008581 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008582 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008583 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008584 networkCapabilitiesRestrictedForCallerPermissions(
8585 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8586 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008587 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008588 nri.mCallingAttributionTag);
8589 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008590 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8591 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008592 // For this notification, arg1 contains the blocked status.
8593 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008594 break;
8595 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008596 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008597 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008598 break;
8599 }
8600 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008601 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008602 final NetworkCapabilities netCap =
8603 networkCapabilitiesRestrictedForCallerPermissions(
8604 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8605 putParcelable(
8606 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008607 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008608 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008609 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008610 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008611 break;
8612 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008613 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008614 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8615 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008616 break;
8617 }
junyulaif2c67e42018-08-07 19:50:45 +08008618 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008619 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008620 msg.arg1 = arg1;
8621 break;
8622 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008623 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008624 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008625 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008626 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008627 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008628 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008629 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008630 }
James Mattis45d81842021-01-10 14:24:24 -08008631 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008632 } catch (RemoteException e) {
8633 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008634 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008635 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008636 }
8637
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008638 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8639 bundle.putParcelable(t.getClass().getSimpleName(), t);
8640 }
8641
Chalard Jean0702f982021-09-16 21:50:07 +09008642 /**
8643 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8644 *
8645 * When a request should be assigned to a new network, it is normally lingered to give
8646 * time for apps to gracefully migrate their connections. When both networks are on the same
8647 * radio, but that radio can't do time-sharing efficiently, this may end up being
8648 * counter-productive because any traffic on the old network may drastically reduce the
8649 * performance of the new network.
8650 * The stack supports a configuration to let modem vendors state that their radio can't
8651 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8652 * from one cell network to another can't be done gracefully.
8653 *
8654 * @param oldNai the old network serving the request
8655 * @param newNai the new network serving the request
8656 * @return whether the switch can be graceful
8657 */
8658 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8659 @NonNull final NetworkAgentInfo newSatisfier) {
8660 if (mCellularRadioTimesharingCapable) return true;
8661 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8662 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8663 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8664 }
8665
Paul Jensenaf94b982014-09-30 15:37:41 -04008666 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008667 if (nai.numRequestNetworkRequests() != 0) {
8668 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8669 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008670 // Ignore listening and track default requests.
8671 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008672 loge("Dead network still had at least " + nr);
8673 break;
8674 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008675 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008676 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008677 }
8678
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008679 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8680 if (oldNetwork == null) {
8681 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8682 return;
8683 }
Chalard Jean49707572019-12-10 21:07:02 +09008684 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008685
8686 // If we get here it means that the last linger timeout for this network expired. So there
8687 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008688 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008689
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008690 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008691 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008692 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008693 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008694 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008695 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008696 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008697 }
8698
James Mattise3ef1912020-12-20 11:09:58 -08008699 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8700 boolean isDefaultChanged = false;
8701 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8702 final NetworkReassignment.RequestReassignment reassignment =
8703 changes.getReassignment(defaultRequestInfo);
8704 if (null == reassignment) {
8705 continue;
8706 }
8707 // reassignment only contains those instances where the satisfying network changed.
8708 isDefaultChanged = true;
8709 // Notify system services of the new default.
8710 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8711 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008712
James Mattise3ef1912020-12-20 11:09:58 -08008713 if (isDefaultChanged) {
8714 // Hold a wakelock for a short time to help apps in migrating to a new default.
8715 scheduleReleaseNetworkTransitionWakelock();
8716 }
8717 }
8718
8719 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8720 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8721 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8722 if (DBG) {
8723 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8724 }
Chalard Jean8e382112019-12-03 20:45:30 +09008725
James Mattisd31bdfa2020-12-23 16:37:26 -08008726 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8727 if (newDefaultNetwork != null) {
8728 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008729 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008730
James Mattisd31bdfa2020-12-23 16:37:26 -08008731 // Set an app level managed default and return since further processing only applies to the
8732 // default network.
8733 if (mDefaultRequest != nri) {
8734 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8735 return;
8736 }
8737
8738 makeDefaultNetwork(newDefaultNetwork);
8739
James Mattise3ef1912020-12-20 11:09:58 -08008740 if (oldDefaultNetwork != null) {
8741 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8742 }
8743 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008744 handleApplyDefaultProxy(null != newDefaultNetwork
8745 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8746 updateTcpBufferSizes(null != newDefaultNetwork
8747 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008748 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008749 }
8750
James Mattisd31bdfa2020-12-23 16:37:26 -08008751 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8752 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8753 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8754 try {
8755 if (VDBG) {
8756 log("Setting default network for " + nri
8757 + " using UIDs " + nri.getUids()
8758 + " with old network " + (oldDefaultNetwork != null
8759 ? oldDefaultNetwork.network().getNetId() : "null")
8760 + " and new network " + (newDefaultNetwork != null
8761 ? newDefaultNetwork.network().getNetId() : "null"));
8762 }
8763 if (nri.getUids().isEmpty()) {
8764 throw new IllegalStateException("makeDefaultForApps called without specifying"
8765 + " any applications to set as the default." + nri);
8766 }
8767 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008768 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008769 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008770 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008771 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008772 }
8773 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008774 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008775 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008776 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008777 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008778 }
8779 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008780 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008781 }
8782 }
8783
Junyu Lai35665cc2022-12-19 17:37:48 +08008784 /**
8785 * Collect restricted uid ranges for the given network and UserHandle, these uids
8786 * are not restricted for matched enterprise networks but being restricted for non-matched
8787 * enterprise networks and non-enterprise networks.
8788 */
8789 @NonNull
8790 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
8791 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
8792 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
8793 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
8794 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
8795
8796 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
8797 // The NC is built from a `ProfileNetworkPreference` which has only one
8798 // enterprise ID, so it's guaranteed to have exactly one.
8799 final int prefId = pref.capabilities.getEnterpriseIds()[0];
8800 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
8801 continue;
8802 }
8803 }
8804
8805 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
8806 pref.capabilities.getUidRanges())) {
8807 throw new IllegalArgumentException(
8808 "Overlapping uid range in preference: " + pref);
8809 }
8810 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
8811 }
8812 return restrictedUidRanges;
8813 }
8814
8815 private void updateProfileAllowedNetworks() {
8816 ensureRunningOnConnectivityServiceThread();
8817 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
8818 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
8819 .getUserHandles(true /* excludeDying */);
8820 if (users.isEmpty()) {
8821 throw new IllegalStateException("No user is available");
8822 }
8823
8824 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8825 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
8826 for (final UserHandle user : users) {
8827 final ArraySet<UidRange> restrictedUidRanges =
8828 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
8829 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
8830 UidRange.createForUser(user), restrictedUidRanges));
8831 }
8832
8833 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
8834 configs.add(new NativeUidRangeConfig(
8835 nai.network.netId, rangesParcel, 0 /* subPriority */));
8836 }
8837
8838 // The netd API replaces the previous configs with the current configs.
8839 // Thus, for network disconnection or preference removal, no need to
8840 // unset previous config. Instead, collecting all currently needed
8841 // configs and issue to netd.
8842 try {
8843 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
8844 } catch (ServiceSpecificException e) {
8845 // Has the interface disappeared since the network was built?
8846 } catch (RemoteException e) {
8847 // Netd died. This usually causes a runtime restart anyway.
8848 }
8849 }
8850
James Mattisd31bdfa2020-12-23 16:37:26 -08008851 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8852 try {
8853 if (null != newDefaultNetwork) {
8854 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8855 } else {
8856 mNetd.networkClearDefault();
8857 }
8858 } catch (RemoteException | ServiceSpecificException e) {
8859 loge("Exception setting default network :" + e);
8860 }
8861 }
8862
Chalard Jean05cbe972019-12-09 11:50:38 +09008863 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008864 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008865 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008866 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008867 processNewlySatisfiedListenRequests(nai);
8868 }
8869
8870 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008871 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8872 if (nri.isMultilayerRequest()) {
8873 continue;
8874 }
8875 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008876 if (!nr.isListen()) continue;
8877 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008878 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008879 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8880 }
8881 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008882 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008883
Chalard Jeancd397a22019-11-22 22:33:33 +09008884 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008885 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8886 if (nri.isMultilayerRequest()) {
8887 continue;
8888 }
8889 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008890 if (!nr.isListen()) continue;
8891 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8892 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008893 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008894 }
8895 }
8896 }
8897
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008898 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008899 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008900 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008901 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008902 @Nullable public final NetworkRequest mOldNetworkRequest;
8903 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008904 @Nullable public final NetworkAgentInfo mOldNetwork;
8905 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008906 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008907 @Nullable final NetworkRequest oldNetworkRequest,
8908 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008909 @Nullable final NetworkAgentInfo oldNetwork,
8910 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008911 mNetworkRequestInfo = networkRequestInfo;
8912 mOldNetworkRequest = oldNetworkRequest;
8913 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008914 mOldNetwork = oldNetwork;
8915 mNewNetwork = newNetwork;
8916 }
Chalard Jean49707572019-12-10 21:07:02 +09008917
8918 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008919 final NetworkRequest requestToShow = null != mNewNetworkRequest
8920 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8921 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008922 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8923 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008924 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008925 }
8926
Chalard Jean46a62372019-12-10 21:25:24 +09008927 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008928
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008929 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008930 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008931 }
8932
8933 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008934 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008935 // The code is never supposed to add two reassignments of the same request. Make
8936 // sure this stays true, but without imposing this expensive check on all
8937 // reassignments on all user devices.
8938 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008939 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008940 throw new IllegalStateException("Trying to reassign ["
8941 + reassignment + "] but already have ["
8942 + existing + "]");
8943 }
8944 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008945 }
Chalard Jean46a62372019-12-10 21:25:24 +09008946 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008947 }
8948
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008949 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008950 // the passed request.
8951 @Nullable
8952 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008953 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008954 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008955 }
8956 return null;
8957 }
Chalard Jean49707572019-12-10 21:07:02 +09008958
8959 public String toString() {
8960 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8961 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008962 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008963 for (final RequestReassignment rr : getRequestReassignments()) {
8964 sj.add(rr.toString());
8965 }
8966 return sj.toString();
8967 }
8968
8969 public String debugString() {
8970 final StringBuilder sb = new StringBuilder();
8971 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008972 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008973 for (final RequestReassignment rr : getRequestReassignments()) {
8974 sb.append("\n ").append(rr);
8975 }
8976 return sb.append("\n").toString();
8977 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008978 }
8979
Chalard Jean24344d72019-12-04 13:32:31 +09008980 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008981 @Nullable final NetworkRequest previousRequest,
8982 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008983 @Nullable final NetworkAgentInfo previousSatisfier,
8984 @Nullable final NetworkAgentInfo newSatisfier,
8985 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008986 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008987 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008988 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008989 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008990 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008991 }
James Mattisa076c532020-12-02 14:12:41 -08008992 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008993 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09008994 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09008995 // If this network switch can't be supported gracefully, the request is not
8996 // lingered. This allows letting go of the network sooner to reclaim some
8997 // performance on the new network, since the radio can't do both at the same
8998 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008999 //
9000 // Also don't linger the request if the old network has been destroyed.
9001 // A destroyed network does not provide actual network connectivity, so
9002 // lingering it is not useful. In particular this ensures that a destroyed
9003 // network is outscored by its replacement,
9004 // then it is torn down immediately instead of being lingered, and any apps that
9005 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009006 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9007 }
Chalard Jean24344d72019-12-04 13:32:31 +09009008 } else {
9009 if (VDBG || DDBG) log(" accepting network in place of null");
9010 }
junyulai0ac374f2020-12-14 18:41:52 +08009011
9012 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9013 // and immediately satisfies a request then remove the timer. This will happen for
9014 // all networks except in the case of an underlying network for a VCN.
9015 if (newSatisfier.isNascent()) {
9016 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009017 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009018 }
9019
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009020 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009021 newSatisfier.unlingerRequest(newRequest.requestId);
9022 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009023 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009024 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009025 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009026 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009027 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009028 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009029 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009030 }
James Mattisa076c532020-12-02 14:12:41 -08009031 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009032 }
James Mattisa076c532020-12-02 14:12:41 -08009033 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009034 }
9035
James Mattisa076c532020-12-02 14:12:41 -08009036 /**
9037 * This function is triggered when something can affect what network should satisfy what
9038 * request, and it computes the network reassignment from the passed collection of requests to
9039 * network match to the one that the system should now have. That data is encoded in an
9040 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9041 * satisfier.
9042 *
9043 * After the reassignment is computed, it is applied to the state objects.
9044 *
9045 * @param networkRequests the nri objects to evaluate for possible network reassignment
9046 * @return NetworkReassignment listing of proposed network assignment changes
9047 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009048 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009049 private NetworkReassignment computeNetworkReassignment(
9050 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009051 final NetworkReassignment changes = new NetworkReassignment();
9052
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009053 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009054 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009055 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009056 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009057 }
Chalard Jean857a1712019-12-10 21:08:07 +09009058
James Mattisa076c532020-12-02 14:12:41 -08009059 for (final NetworkRequestInfo nri : networkRequests) {
9060 // Non-multilayer listen requests can be ignored.
9061 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9062 continue;
9063 }
9064 NetworkAgentInfo bestNetwork = null;
9065 NetworkRequest bestRequest = null;
9066 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009067 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009068 // Stop evaluating as the highest possible priority request is satisfied.
9069 if (null != bestNetwork) {
9070 bestRequest = req;
9071 break;
9072 }
9073 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009074 if (null == bestNetwork && isDefaultBlocked(nri)) {
9075 // Remove default networking if disallowed for managed default requests.
9076 bestNetwork = mNoServiceNetwork;
9077 }
9078 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009079 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009080 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009081 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009082 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009083 }
9084 return changes;
9085 }
9086
James Mattisa076c532020-12-02 14:12:41 -08009087 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9088 return new HashSet<>(mNetworkRequests.values());
9089 }
9090
Paul Jensenc88b39b2015-06-16 14:27:36 -04009091 /**
James Mattisa076c532020-12-02 14:12:41 -08009092 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009093 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009094 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009095 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009096 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9097 }
9098
9099 /**
9100 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9101 * being disconnected.
9102 */
9103 private void rematchNetworksAndRequests(
9104 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9105 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009106 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009107 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009108 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009109 final long computed = SystemClock.elapsedRealtime();
9110 applyNetworkReassignment(changes, start);
9111 final long applied = SystemClock.elapsedRealtime();
9112 issueNetworkNeeds();
9113 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009114 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009115 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9116 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009117 log(changes.debugString());
9118 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009119 // Shorter form, only one line of log
9120 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9121 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009122 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009123 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009124
Chalard Jeand7f762d2019-12-10 19:01:29 +09009125 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009126 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009127 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009128
9129 // Since most of the time there are only 0 or 1 background networks, it would probably
9130 // be more efficient to just use an ArrayList here. TODO : measure performance
9131 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9132 for (final NetworkAgentInfo nai : nais) {
9133 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9134 }
9135
Chalard Jeand7f762d2019-12-10 19:01:29 +09009136 // First, update the lists of satisfied requests in the network agents. This is necessary
9137 // because some code later depends on this state to be correct, most prominently computing
9138 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009139 for (final NetworkReassignment.RequestReassignment event :
9140 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009141 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9142 event.mOldNetworkRequest, event.mNewNetworkRequest,
9143 event.mOldNetwork, event.mNewNetwork,
9144 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009145 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009146
James Mattise3ef1912020-12-20 11:09:58 -08009147 // Process default network changes if applicable.
9148 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009149
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009150 // Notify requested networks are available after the default net is switched, but
9151 // before LegacyTypeTracker sends legacy broadcasts
9152 for (final NetworkReassignment.RequestReassignment event :
9153 changes.getRequestReassignments()) {
9154 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009155 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009156 } else {
James Mattisa076c532020-12-02 14:12:41 -08009157 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009158 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009159 }
9160 }
9161
junyulai0ac374f2020-12-14 18:41:52 +08009162 // Update the inactivity state before processing listen callbacks, because the background
9163 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009164 // just yet though, because they have to be sent after the listens are processed to keep
9165 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009166 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009167 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009168 // Rematching may have altered the inactivity state of some networks, so update all
9169 // inactivity timers. updateInactivityState reads the state from the network agent
9170 // and does nothing if the state has not changed : the source of truth is controlled
9171 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9172 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009173 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009174 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009175 }
9176 }
9177
Chalard Jeanb10ab412019-12-11 14:12:30 +09009178 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009179 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009180 // Process listen requests and update capabilities if the background state has
9181 // changed for this network. For consistency with previous behavior, send onLost
9182 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009183 processNewlyLostListenRequests(nai);
9184 if (oldBackground != nai.isBackgroundNetwork()) {
9185 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009186 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009187 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009188 }
9189
junyulai0ac374f2020-12-14 18:41:52 +08009190 for (final NetworkAgentInfo nai : inactiveNetworks) {
9191 // For nascent networks, if connecting with no foreground request, skip broadcasting
9192 // LOSING for backward compatibility. This is typical when mobile data connected while
9193 // wifi connected with mobile data always-on enabled.
9194 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009195 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009196 }
9197
James Mattise3ef1912020-12-20 11:09:58 -08009198 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009199
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009200 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009201 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009202 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009203 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009204 // This network has active linger timers and no requests, but is not
9205 // lingering. Linger it.
9206 //
9207 // One way (the only way?) this can happen if this network is unvalidated
9208 // and became unneeded due to another network improving its score to the
9209 // point where this network will no longer be able to satisfy any requests
9210 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009211 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009212 notifyNetworkLosing(nai, now);
9213 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009214 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009215 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009216 teardownUnneededNetwork(nai);
9217 }
9218 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009219 }
9220 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009221
Chalard Jean62edfd82019-12-02 18:39:29 +09009222 /**
9223 * Apply a change in background state resulting from rematching networks with requests.
9224 *
9225 * During rematch, a network may change background states by starting to satisfy or stopping
9226 * to satisfy a foreground request. Listens don't count for this. When a network changes
9227 * background states, its capabilities need to be updated and callbacks fired for the
9228 * capability change.
9229 *
9230 * @param nai The network that changed background states
9231 */
9232 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9233 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9234 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9235 updateNetworkPermissions(nai, newNc);
9236 nai.getAndSetNetworkCapabilities(newNc);
9237 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9238 }
9239
Chalard Jeanf0344532019-11-19 19:23:38 +09009240 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009241 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009242 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009243 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9244 changes.getReassignment(mDefaultRequest);
9245 final NetworkAgentInfo oldDefaultNetwork =
9246 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9247 final NetworkAgentInfo newDefaultNetwork =
9248 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009249
Chalard Jean5b409c72021-02-04 13:12:59 +09009250 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009251 // Maintain the illusion : since the legacy API only understands one network at a time,
9252 // if the default network changed, apps should see a disconnected broadcast for the
9253 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009254 if (oldDefaultNetwork != null) {
9255 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9256 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009257 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009258 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009259 // The new default network can be newly null if and only if the old default
9260 // network doesn't satisfy the default request any more because it lost a
9261 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009262 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009263 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009264 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009265 }
9266 }
9267
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009268 // Now that all the callbacks have been sent, send the legacy network broadcasts
9269 // as needed. This is necessary so that legacy requests correctly bind dns
9270 // requests to this network. The legacy users are listening for this broadcast
9271 // and will generally do a dns request so they can ensureRouteToHost and if
9272 // they do that before the callbacks happen they'll use the default network.
9273 //
9274 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9275 // callbacks, but if apps can receive the broadcast before the callback, they still might
9276 // have an inconsistent view of networking.
9277 //
9278 // This *does* introduce a race where if the user uses the new api
9279 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9280 // they may get old info. Reverse this after the old startUsing api is removed.
9281 // This is on top of the multiple intent sequencing referenced in the todo above.
9282 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009283 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009284 addNetworkToLegacyTypeTracker(nai);
9285 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009286 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009287 }
9288
Chalard Jean0354d8c2021-01-12 10:58:56 +09009289 private void issueNetworkNeeds() {
9290 ensureRunningOnConnectivityServiceThread();
9291 for (final NetworkOfferInfo noi : mNetworkOffers) {
9292 issueNetworkNeeds(noi);
9293 }
9294 }
9295
9296 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9297 ensureRunningOnConnectivityServiceThread();
9298 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9299 informOffer(nri, noi.offer, mNetworkRanker);
9300 }
9301 }
9302
9303 /**
9304 * Inform a NetworkOffer about any new situation of a request.
9305 *
9306 * This function handles updates to offers. A number of events may happen that require
9307 * updating the registrant for this offer about the situation :
9308 * • The offer itself was updated. This may lead the offer to no longer being able
9309 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9310 * or conversely being strengthened enough to beat the satisfier (and therefore
9311 * start being needed)
9312 * • The network satisfying a request changed (including cases where the request
9313 * starts or stops being satisfied). The new network may be a stronger or weaker
9314 * match than the old one, possibly affecting whether the offer is needed.
9315 * • The network satisfying a request updated their score. This may lead the offer
9316 * to no longer be able to beat it if the current satisfier got better, or
9317 * conversely start being a good choice if the current satisfier got weaker.
9318 *
9319 * @param nri The request
9320 * @param offer The offer. This may be an updated offer.
9321 */
9322 private static void informOffer(@NonNull NetworkRequestInfo nri,
9323 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9324 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9325 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009326
9327 // Multi-layer requests have a currently active request, the one being satisfied.
9328 // Since the system will try to bring up a better network than is currently satisfying
9329 // the request, NetworkProviders need to be told the offers matching the requests *above*
9330 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9331 // not needed, and the offer is needed for the active request iff the offer can beat
9332 // the satisfier.
9333 // For non-multilayer requests, the logic above gracefully degenerates to only the
9334 // last case.
9335 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9336 // providers that the offer is needed for this request, until the active request is found.
9337 // In a second phase, deal with the currently active request. In a third phase, inform
9338 // the providers that offer is unneeded for the remaining requests.
9339
9340 // First phase : inform providers of all requests above the active request.
9341 int i;
9342 for (i = 0; nri.mRequests.size() > i; ++i) {
9343 final NetworkRequest request = nri.mRequests.get(i);
9344 if (activeRequest == request) break; // Found the active request : go to phase 2
9345 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9346 // Since this request is higher-priority than the one currently satisfied, if the
9347 // offer can satisfy it, the provider should try and bring up the network for sure ;
9348 // no need to even ask the ranker – an offer that can satisfy is always better than
9349 // no network. Hence tell the provider so unless it already knew.
9350 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9351 offer.onNetworkNeeded(request);
9352 }
9353 }
9354
9355 // Second phase : deal with the active request (if any)
9356 if (null != activeRequest && activeRequest.isRequest()) {
9357 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009358 // If an offer can satisfy the request, it is considered needed if it is currently
9359 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009360 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009361 && satisfier.factorySerialNumber == offer.providerId
9362 && activeRequest.canBeSatisfiedBy(offer.caps);
9363 final boolean newNeeded = currentlyServing
9364 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009365 if (newNeeded != oldNeeded) {
9366 if (newNeeded) {
9367 offer.onNetworkNeeded(activeRequest);
9368 } else {
9369 // The offer used to be able to beat the satisfier. Now it can't.
9370 offer.onNetworkUnneeded(activeRequest);
9371 }
9372 }
9373 }
9374
9375 // Third phase : inform the providers that the offer isn't needed for any request
9376 // below the active one.
9377 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9378 final NetworkRequest request = nri.mRequests.get(i);
9379 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9380 // Since this request is lower-priority than the one currently satisfied, if the
9381 // offer can satisfy it, the provider should not try and bring up the network.
9382 // Hence tell the provider so unless it already knew.
9383 if (offer.neededFor(request)) {
9384 offer.onNetworkUnneeded(request);
9385 }
9386 }
9387 }
9388
Chalard Jean61c79252019-11-07 23:07:32 +09009389 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9390 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9391 NetworkRequest nr = nai.requestAt(i);
9392 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9393 // legacy type tracker filters out repeat adds
9394 mLegacyTypeTracker.add(nr.legacyType, nai);
9395 }
9396 }
9397
9398 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009399 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009400 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9401 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9402 if (nai.isVPN()) {
9403 mLegacyTypeTracker.add(TYPE_VPN, nai);
9404 }
9405 }
9406
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009407 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009408 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009409 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009410 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009411 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009412 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009413
Chalard Jean254bd162022-08-25 13:04:51 +09009414 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009415 // Don't repeat publish.
9416 if (newInetCondition == mDefaultInetConditionPublished) return;
9417
9418 mDefaultInetConditionPublished = newInetCondition;
9419 sendInetConditionBroadcast(nai.networkInfo);
9420 }
9421
Chalard Jeand61375d2020-01-14 22:46:36 +09009422 @NonNull
9423 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9424 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009425 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009426 final boolean suspended =
9427 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9428 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9429 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9430 // state. This is because the network could have been suspended before connecting,
9431 // or it could be disconnecting while being suspended, and in both these cases
9432 // the state should not be overridden. Note that the only detailed state that
9433 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9434 // worry about multiple different substates of CONNECTED.
9435 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9436 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009437 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9438 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9439 // network agent is created, then goes to suspended, then goes out of suspended without
9440 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009441 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009442 ? NetworkInfo.DetailedState.CONNECTED
9443 : NetworkInfo.DetailedState.CONNECTING,
9444 info.getReason(),
9445 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009446 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009447 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009448 return newInfo;
9449 }
9450
9451 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9452 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9453
Erik Kline99f301b2017-02-15 19:59:17 +09009454 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009455 NetworkInfo oldInfo = null;
9456 synchronized (networkAgent) {
9457 oldInfo = networkAgent.networkInfo;
9458 networkAgent.networkInfo = newInfo;
9459 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009460
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009461 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009462 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9463 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009464 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009465
Chalard Jean254bd162022-08-25 13:04:51 +09009466 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009467 && (state == NetworkInfo.State.CONNECTED
9468 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009469
9470 // A network that has just connected has zero requests and is thus a foreground network.
9471 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9472
Luke Huangfdd11f82019-04-09 18:41:49 +08009473 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009474 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009475 // Initialize the network's capabilities to their starting values according to the
9476 // underlying networks. This ensures that the capabilities are correct before
9477 // anything happens to the network.
9478 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009479 }
Chalard Jean254bd162022-08-25 13:04:51 +09009480 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009481 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009482 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009483 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009484 }
9485
Chalard Jean254bd162022-08-25 13:04:51 +09009486 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9487 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009488
lucaslin45e639b2019-04-03 17:09:28 +08009489 // NetworkCapabilities need to be set before sending the private DNS config to
9490 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009491 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9492
Erik Kline9a62f012018-03-21 07:18:33 -07009493 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009494 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9495 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009496
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009497 // If a rate limit has been configured and is applicable to this network (network
9498 // provides internet connectivity), apply it. The tc police filter cannot be attached
9499 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9500 // updateInterfaces -> INetd#networkAddInterface.
9501 // Note: in case of a system server crash, the NetworkController constructor in netd
9502 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9503 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9504 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9505 mIngressRateLimit);
9506 }
9507
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009508 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9509 // command must be sent after updating LinkProperties to maximize chances of
9510 // NetworkMonitor seeing the correct LinkProperties when starting.
9511 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009512 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009513 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009514 }
Chalard Jeand4900722022-02-06 12:25:38 +09009515 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9516 params.networkAgentConfig = networkAgent.networkAgentConfig;
9517 params.networkCapabilities = networkAgent.networkCapabilities;
9518 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9519 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009520 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9521 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9522 // call that would cause a Log.wtf to be emitted from the system_server process, and
9523 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9524 // process to check the interface version, just use an SDK check. NetworkStack will
9525 // always be new enough when running on T+.
9526 if (SdkLevel.isAtLeastT()) {
9527 networkAgent.networkMonitor().notifyNetworkConnected(params);
9528 } else {
9529 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9530 params.networkCapabilities);
9531 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009532 final long delay = activelyPreferBadWifi()
9533 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9534 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9535 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009536
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009537 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9538 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9539 // capabilities, so it only needs to be done once on initial connect, not every time the
9540 // network's capabilities change. Note that we do this before rematching the network,
9541 // so we could decide to tear it down immediately afterwards. That's fine though - on
9542 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9543 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009544 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009545
junyulai0ac374f2020-12-14 18:41:52 +08009546 // Before first rematching networks, put an inactivity timer without any request, this
9547 // allows {@code updateInactivityState} to update the state accordingly and prevent
9548 // tearing down for any {@code unneeded} evaluation in this period.
9549 // Note that the timer will not be rescheduled since the expiry time is
9550 // fixed after connection regardless of the network satisfying other requests or not.
9551 // But it will be removed as soon as the network satisfies a request for the first time.
9552 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9553 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009554 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009555
Paul Jensen05e85ee2014-09-11 11:00:39 -04009556 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009557 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009558
9559 // This has to happen after matching the requests, because callbacks are just requests.
9560 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009561 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009562 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009563 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009564 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009565 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009566 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009567 if (networkAgent.isVPN()) {
9568 // As the active or bound network changes for apps, broadcast the default proxy, as
9569 // apps may need to update their proxy data. This is called after disconnecting from
9570 // VPN to make sure we do not broadcast the old proxy data.
9571 // TODO(b/122649188): send the broadcast only to VPN users.
9572 mProxyTracker.sendProxyBroadcast();
9573 }
Chalard Jean254bd162022-08-25 13:04:51 +09009574 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9575 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009576 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009577 }
9578 }
9579
Chalard Jean28018572020-12-21 18:36:52 +09009580 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009581 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9582 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009583 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009584 }
9585
Erik Kline99f301b2017-02-15 19:59:17 +09009586 // Notify only this one new request of the current state. Transfer all the
9587 // current state by calling NetworkCapabilities and LinkProperties callbacks
9588 // so that callers can be guaranteed to have as close to atomicity in state
9589 // transfer as can be supported by this current API.
9590 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009591 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009592 if (nri.mPendingIntent != null) {
9593 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9594 // Attempt no subsequent state pushes where intents are involved.
9595 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009596 }
Erik Kline99f301b2017-02-15 19:59:17 +09009597
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009598 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009599 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009600 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9601 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9602 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009603 }
9604
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009605 // Notify the requests on this NAI that the network is now lingered.
9606 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009607 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009608 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9609 }
9610
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009611 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9612 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9613 return vpnBlocked
9614 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9615 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9616 }
9617
9618 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9619 if (blockedReasons == BLOCKED_REASON_NONE) {
9620 mUidBlockedReasons.delete(uid);
9621 } else {
9622 mUidBlockedReasons.put(uid, blockedReasons);
9623 }
9624 }
9625
junyulaif2c67e42018-08-07 19:50:45 +08009626 /**
9627 * Notify of the blocked state apps with a registered callback matching a given NAI.
9628 *
9629 * Unlike other callbacks, blocked status is different between each individual uid. So for
9630 * any given nai, all requests need to be considered according to the uid who filed it.
9631 *
9632 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009633 * @param oldMetered True if the previous network capabilities were metered.
9634 * @param newMetered True if the current network capabilities are metered.
9635 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9636 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009637 */
9638 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009639 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9640 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009641
9642 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9643 NetworkRequest nr = nai.requestAt(i);
9644 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009645
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009646 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9647 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9648 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009649 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009650 : oldVpnBlocked;
9651
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009652 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9653 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9654 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009655 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009656 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009657 }
9658 }
9659 }
9660
9661 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009662 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009663 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009664 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009665 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009666 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009667 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009668 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009669 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009670
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009671 final int oldBlockedState = getBlockedState(
9672 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9673 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9674 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009675 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009676 }
junyulaif2c67e42018-08-07 19:50:45 +08009677 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9678 NetworkRequest nr = nai.requestAt(i);
9679 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009680 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009681 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9682 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009683 }
9684 }
9685 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009686 }
9687
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009688 @VisibleForTesting
9689 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009690 // The NetworkInfo we actually send out has no bearing on the real
9691 // state of affairs. For example, if the default connection is mobile,
9692 // and a request for HIPRI has just gone away, we need to pretend that
9693 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9694 // the state to DISCONNECTED, even though the network is of type MOBILE
9695 // and is still connected.
9696 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9697 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009698 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009699 if (state != DetailedState.DISCONNECTED) {
9700 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009701 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009702 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009703 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009704 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9705 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9706 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9707 if (info.isFailover()) {
9708 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9709 nai.networkInfo.setFailover(false);
9710 }
9711 if (info.getReason() != null) {
9712 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9713 }
9714 if (info.getExtraInfo() != null) {
9715 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9716 }
9717 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009718 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009719 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009720 if (newDefaultAgent != null) {
9721 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9722 newDefaultAgent.networkInfo);
9723 } else {
9724 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9725 }
9726 }
9727 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9728 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009729 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009730 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009731 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009732 }
9733 }
9734 }
9735
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009736 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009737 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009738 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009739 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009740 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009741 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9742 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009743 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9744 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009745 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009746 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009747 } else {
9748 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9749 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009750 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009751 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009752
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009753 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9754 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9755 }
9756
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009757 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009758 * Returns the list of all interfaces that could be used by network traffic that does not
9759 * explicitly specify a network. This includes the default network, but also all VPNs that are
9760 * currently connected.
9761 *
9762 * Must be called on the handler thread.
9763 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009764 @NonNull
9765 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009766 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009767 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009768 final Set<Integer> activeNetIds = new ArraySet<>();
9769 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9770 if (nri.isBeingSatisfied()) {
9771 activeNetIds.add(nri.getSatisfier().network().netId);
9772 }
9773 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009774 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009775 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009776 defaultNetworks.add(nai.network);
9777 }
9778 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009779 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009780 }
9781
9782 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009783 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9784 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009785 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009786 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009787 ensureRunningOnConnectivityServiceThread();
9788 String activeIface = null;
9789 LinkProperties activeLinkProperties = getActiveLinkProperties();
9790 if (activeLinkProperties != null) {
9791 activeIface = activeLinkProperties.getInterfaceName();
9792 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009793
junyulai2050bed2021-01-23 09:46:34 +08009794 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009795 try {
junyulaide41fc22021-01-22 22:46:01 +08009796 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009797 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009798 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9799 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009800 } catch (Exception ignored) {
9801 }
9802 }
9803
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009804 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009805 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009806 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009807 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009808 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009809
9810 if (!TextUtils.isEmpty(settingUrl)) {
9811 return settingUrl;
9812 }
9813
9814 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009815 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009816 if (!TextUtils.isEmpty(settingUrl)) {
9817 return settingUrl;
9818 }
9819
9820 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009821 }
9822
9823 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009824 public void startNattKeepalive(Network network, int intervalSeconds,
9825 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009826 enforceKeepalivePermission();
9827 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009828 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00009829 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
9830 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
9831 // false because there is no way and no plan to configure automaticOnOffKeepalives
9832 // in this deprecated method.
9833 false /* automaticOnOffKeepalives */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009834 }
9835
9836 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009837 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009838 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00009839 String dstAddr, boolean automaticOnOffKeepalives) {
Josh Gao461a1222020-06-16 15:58:11 -07009840 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009841 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009842 mKeepaliveTracker.startNattKeepalive(
9843 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9844 intervalSeconds, cb,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00009845 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT, automaticOnOffKeepalives);
Josh Gao461a1222020-06-16 15:58:11 -07009846 } finally {
9847 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9848 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009849 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9850 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009851 }
9852 }
junyulaid05a1922019-01-15 11:32:44 +08009853 }
9854
9855 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009856 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009857 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009858 try {
9859 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009860 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009861 mKeepaliveTracker.startTcpKeepalive(
9862 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9863 } finally {
9864 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9865 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009866 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9867 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009868 }
9869 }
junyulai0835a1e2019-01-08 20:04:33 +08009870 }
9871
9872 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +09009873 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009874 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +09009875 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
9876 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009877 }
9878
9879 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009880 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009881 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009882
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009883 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009884 final long token = Binder.clearCallingIdentity();
9885 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009886 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9887 UserHandle.getUserHandleForUid(uid))) {
9888 return;
9889 }
9890
Heemin Seogdb8489d2019-06-12 09:21:44 -07009891 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9892 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009893
9894 // Turn airplane mode off
9895 setAirplaneMode(false);
9896
9897 // restore private DNS settings to default mode (opportunistic)
9898 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9899 UserHandle.getUserHandleForUid(uid))) {
9900 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9901 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9902 }
9903
9904 Settings.Global.putString(mContext.getContentResolver(),
9905 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009906 } finally {
9907 Binder.restoreCallingIdentity(token);
9908 }
Stuart Scottd5463642015-04-02 18:00:02 -07009909 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009910
Ricky Wai7097cc92018-01-23 04:09:45 +00009911 @Override
9912 public byte[] getNetworkWatchlistConfigHash() {
9913 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9914 if (nwm == null) {
9915 loge("Unable to get NetworkWatchlistManager");
9916 return null;
9917 }
9918 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9919 return nwm.getWatchlistConfigHash();
9920 }
9921
Hugo Benichibe0c7652016-05-31 16:28:06 +09009922 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009923 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009924 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009925 }
Hugo Benichif4210292017-04-21 15:07:12 +09009926
9927 private static boolean toBool(int encodedBoolean) {
9928 return encodedBoolean != 0; // Only 0 means false.
9929 }
9930
9931 private static int encodeBool(boolean b) {
9932 return b ? 1 : 0;
9933 }
mswest4632928412018-03-12 10:34:34 -07009934
9935 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009936 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9937 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9938 @NonNull String[] args) {
9939 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9940 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009941 }
9942
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009943 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009944 @Override
9945 public int onCommand(String cmd) {
9946 if (cmd == null) {
9947 return handleDefaultCommands(cmd);
9948 }
9949 final PrintWriter pw = getOutPrintWriter();
9950 try {
9951 switch (cmd) {
9952 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009953 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
9954 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -07009955 final String action = getNextArg();
9956 if ("enable".equals(action)) {
9957 setAirplaneMode(true);
9958 return 0;
9959 } else if ("disable".equals(action)) {
9960 setAirplaneMode(false);
9961 return 0;
9962 } else if (action == null) {
9963 final ContentResolver cr = mContext.getContentResolver();
9964 final int enabled = Settings.Global.getInt(cr,
9965 Settings.Global.AIRPLANE_MODE_ON);
9966 pw.println(enabled == 0 ? "disabled" : "enabled");
9967 return 0;
9968 } else {
9969 onHelp();
9970 return -1;
9971 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009972 case "reevaluate":
9973 // Usage : adb shell cmd connectivity reevaluate <netId>
9974 // If netId is omitted, then reevaluate the default network
9975 final String netId = getNextArg();
9976 final NetworkAgentInfo nai;
9977 if (null == netId) {
9978 // Note that the command is running on the wrong thread to call this,
9979 // so this could in principle return stale data. But it can't crash.
9980 nai = getDefaultNetwork();
9981 } else {
9982 // If netId can't be parsed, this throws NumberFormatException, which
9983 // is passed back to adb who prints it.
9984 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
9985 }
9986 if (null == nai) {
9987 pw.println("Unknown network (net ID not found or no default network)");
9988 return 0;
9989 }
9990 Log.d(TAG, "Reevaluating network " + nai.network);
9991 reportNetworkConnectivity(nai.network, !nai.isValidated());
9992 return 0;
mswest4632928412018-03-12 10:34:34 -07009993 default:
9994 return handleDefaultCommands(cmd);
9995 }
9996 } catch (Exception e) {
9997 pw.println(e);
9998 }
9999 return -1;
10000 }
10001
10002 @Override
10003 public void onHelp() {
10004 PrintWriter pw = getOutPrintWriter();
10005 pw.println("Connectivity service commands:");
10006 pw.println(" help");
10007 pw.println(" Print this help text.");
10008 pw.println(" airplane-mode [enable|disable]");
10009 pw.println(" Turn airplane mode on or off.");
10010 pw.println(" airplane-mode");
10011 pw.println(" Get airplane mode.");
10012 }
10013 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010014
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010015 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010016 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10017 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10018 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010019 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010020 }
10021
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010022 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10023 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010024 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10025 final TransportInfo newInfo = nc.getTransportInfo();
10026 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10027 return;
10028 }
10029 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010030 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010031 }
10032 }
10033
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010034 /**
10035 * @param connectionInfo the connection to resolve.
10036 * @return {@code uid} if the connection is found and the app has permission to observe it
10037 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10038 * connection is not found.
10039 */
10040 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010041 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10042 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10043 }
10044
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010045 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010046 connectionInfo.local, connectionInfo.remote);
10047
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010048 if (uid == INVALID_UID) return uid; // Not found.
10049
10050 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10051 // VPN, if any, that applies to the UID that owns the connection.
10052 if (checkNetworkStackPermission()) return uid;
10053
10054 final NetworkAgentInfo vpn = getVpnForUid(uid);
10055 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010056 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010057 return INVALID_UID;
10058 }
10059
10060 return uid;
10061 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010062
Benedict Wong493e04b2018-11-09 14:45:34 -080010063 /**
10064 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10065 *
10066 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10067 */
10068 @Override
10069 public IBinder startOrGetTestNetworkService() {
10070 synchronized (mTNSLock) {
10071 TestNetworkService.enforceTestNetworkPermissions(mContext);
10072
10073 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010074 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010075 }
10076
10077 return mTNS;
10078 }
10079 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010080
Cody Kesting73708bf2019-12-18 10:57:50 -080010081 /**
10082 * Handler used for managing all Connectivity Diagnostics related functions.
10083 *
10084 * @see android.net.ConnectivityDiagnosticsManager
10085 *
10086 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10087 */
10088 @VisibleForTesting
10089 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010090 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10091
Cody Kesting73708bf2019-12-18 10:57:50 -080010092 /**
10093 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10094 * android.net.ConnectivityDiagnosticsManager}.
10095 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10096 * NetworkRequestInfo to be registered
10097 */
10098 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10099
10100 /**
10101 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10102 * android.net.ConnectivityDiagnosticsManager}.
10103 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10104 * arg1 = the uid of the caller
10105 */
10106 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10107
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010108 /**
10109 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010110 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010111 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10112 * NetworkMonitor.
10113 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010114 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010115 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010116
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010117 /**
10118 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10119 * been detected on the network.
10120 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10121 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10122 * arg2 = NetID.
10123 * data = PersistableBundle of extras passed from NetworkMonitor.
10124 */
10125 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10126
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010127 /**
10128 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10129 * the platform. This event will invoke {@link
10130 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10131 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010132 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010133 */
10134 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10135
Cody Kesting73708bf2019-12-18 10:57:50 -080010136 private ConnectivityDiagnosticsHandler(Looper looper) {
10137 super(looper);
10138 }
10139
10140 @Override
10141 public void handleMessage(Message msg) {
10142 switch (msg.what) {
10143 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10144 handleRegisterConnectivityDiagnosticsCallback(
10145 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10146 break;
10147 }
10148 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10149 handleUnregisterConnectivityDiagnosticsCallback(
10150 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10151 break;
10152 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010153 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010154 final ConnectivityReportEvent reportEvent =
10155 (ConnectivityReportEvent) msg.obj;
10156
Aaron Huang959d3642021-01-21 15:47:41 +080010157 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010158 break;
10159 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010160 case EVENT_DATA_STALL_SUSPECTED: {
10161 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010162 final Pair<Long, PersistableBundle> arg =
10163 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010164 if (nai == null) break;
10165
Aaron Huang959d3642021-01-21 15:47:41 +080010166 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010167 break;
10168 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010169 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010170 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010171 break;
10172 }
10173 default: {
10174 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10175 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010176 }
10177 }
10178 }
10179
10180 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10181 @VisibleForTesting
10182 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10183 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10184 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010185 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010186
10187 @VisibleForTesting
10188 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010189 @NonNull IConnectivityDiagnosticsCallback cb,
10190 @NonNull NetworkRequestInfo nri,
10191 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010192 mCb = cb;
10193 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010194 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010195 }
10196
10197 @Override
10198 public void binderDied() {
10199 log("ConnectivityDiagnosticsCallback IBinder died.");
10200 unregisterConnectivityDiagnosticsCallback(mCb);
10201 }
10202 }
10203
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010204 /**
10205 * Class used for sending information from {@link
10206 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10207 */
10208 private static class NetworkTestedResults {
10209 private final int mNetId;
10210 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010211 @Nullable private final String mRedirectUrl;
10212
10213 private NetworkTestedResults(
10214 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10215 mNetId = netId;
10216 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010217 mRedirectUrl = redirectUrl;
10218 }
10219 }
10220
10221 /**
10222 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10223 * ConnectivityDiagnosticsHandler}.
10224 */
10225 private static class ConnectivityReportEvent {
10226 private final long mTimestampMillis;
10227 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010228 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010229
Aaron Huang959d3642021-01-21 15:47:41 +080010230 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10231 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010232 mTimestampMillis = timestampMillis;
10233 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010234 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010235 }
10236 }
10237
Cody Kestingf1120be2020-08-03 18:01:40 -070010238 /**
10239 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10240 * ConnectivityDiagnosticsHandler}.
10241 */
10242 private static class ReportedNetworkConnectivityInfo {
10243 public final boolean hasConnectivity;
10244 public final boolean isNetworkRevalidating;
10245 public final int reporterUid;
10246 @NonNull public final NetworkAgentInfo nai;
10247
10248 private ReportedNetworkConnectivityInfo(
10249 boolean hasConnectivity,
10250 boolean isNetworkRevalidating,
10251 int reporterUid,
10252 @NonNull NetworkAgentInfo nai) {
10253 this.hasConnectivity = hasConnectivity;
10254 this.isNetworkRevalidating = isNetworkRevalidating;
10255 this.reporterUid = reporterUid;
10256 this.nai = nai;
10257 }
10258 }
10259
Cody Kesting73708bf2019-12-18 10:57:50 -080010260 private void handleRegisterConnectivityDiagnosticsCallback(
10261 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10262 ensureRunningOnConnectivityServiceThread();
10263
10264 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010265 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010266 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10267
James Mattis64b8b0f2020-11-24 17:40:49 -080010268 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10269 // confusing for these networks to change when an NRI is satisfied in another layer.
10270 if (nri.isMultilayerRequest()) {
10271 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10272 + "network requests.");
10273 }
10274
Cody Kesting73708bf2019-12-18 10:57:50 -080010275 // This means that the client registered the same callback multiple times. Do
10276 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010277 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010278 if (VDBG) log("Diagnostics callback is already registered");
10279
10280 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10281 // incremented when the NetworkRequestInfo is created as part of
10282 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010283 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010284 return;
10285 }
10286
Cody Kesting31f1ff62020-03-05 10:46:02 -080010287 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010288
10289 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010290 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010291 } catch (RemoteException e) {
10292 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010293 return;
10294 }
10295
10296 // Once registered, provide ConnectivityReports for matching Networks
10297 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10298 synchronized (mNetworkForNetId) {
10299 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10300 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010301 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10302 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010303 matchingNetworks.add(nai);
10304 }
10305 }
10306 }
10307 for (final NetworkAgentInfo nai : matchingNetworks) {
10308 final ConnectivityReport report = nai.getConnectivityReport();
10309 if (report == null) {
10310 continue;
10311 }
10312 if (!checkConnectivityDiagnosticsPermissions(
10313 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10314 continue;
10315 }
10316
10317 try {
10318 cb.onConnectivityReportAvailable(report);
10319 } catch (RemoteException e) {
10320 // Exception while sending the ConnectivityReport. Move on to the next network.
10321 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010322 }
10323 }
10324
10325 private void handleUnregisterConnectivityDiagnosticsCallback(
10326 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10327 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010328 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010329
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010330 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10331 mConnectivityDiagnosticsCallbacks.remove(iCb);
10332 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010333 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10334 return;
10335 }
10336
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010337 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010338
Cody Kesting70fa2b22020-12-02 12:16:56 -080010339 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10340 // (if the Binder died)
10341 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10342 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010343 return;
10344 }
10345
Cody Kesting46cb1672020-03-04 13:35:20 -080010346 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10347 // incremented when the NetworkRequestInfo is created as part of
10348 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010349 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010350
Cody Kesting31f1ff62020-03-05 10:46:02 -080010351 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010352 }
10353
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010354 private void handleNetworkTestedWithExtras(
10355 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10356 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010357 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010358 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010359 final ConnectivityReport report =
10360 new ConnectivityReport(
10361 reportEvent.mNai.network,
10362 reportEvent.mTimestampMillis,
10363 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010364 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010365 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010366 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010367
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010368 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010369 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010370 for (final IConnectivityDiagnosticsCallback cb : results) {
10371 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010372 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010373 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010374 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010375 }
10376 }
10377 }
10378
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010379 private void handleDataStallSuspected(
10380 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10381 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010382 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010383 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010384 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010385 new DataStallReport(
10386 nai.network,
10387 timestampMillis,
10388 detectionMethod,
10389 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010390 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010391 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010392 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010393 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010394 for (final IConnectivityDiagnosticsCallback cb : results) {
10395 try {
10396 cb.onDataStallSuspected(report);
10397 } catch (RemoteException ex) {
10398 loge("Error invoking onDataStallSuspected", ex);
10399 }
10400 }
10401 }
10402
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010403 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010404 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10405 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10406 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10407
10408 // If the Network is being re-validated as a result of this call to
10409 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10410 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010411 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010412 getMatchingPermissionedCallbacks(
10413 nai,
10414 reportedNetworkConnectivityInfo.isNetworkRevalidating
10415 ? Process.INVALID_UID
10416 : reportedNetworkConnectivityInfo.reporterUid);
10417
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010418 for (final IConnectivityDiagnosticsCallback cb : results) {
10419 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010420 cb.onNetworkConnectivityReported(
10421 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010422 } catch (RemoteException ex) {
10423 loge("Error invoking onNetworkConnectivityReported", ex);
10424 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010425
10426 // If the Network isn't re-validating, also provide the cached report. If there is no
10427 // cached report, the Network is still being validated and a report will be sent once
10428 // validation is complete. Note that networks which never undergo validation will still
10429 // have a cached ConnectivityReport with RESULT_SKIPPED.
10430 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10431 try {
10432 cb.onConnectivityReportAvailable(cachedReport);
10433 } catch (RemoteException ex) {
10434 loge("Error invoking onConnectivityReportAvailable", ex);
10435 }
10436 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010437 }
10438 }
10439
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010440 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010441 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10442 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010443 sanitized.setUids(null);
10444 sanitized.setAdministratorUids(new int[0]);
10445 sanitized.setOwnerUid(Process.INVALID_UID);
10446 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010447 }
10448
Cody Kestingf1120be2020-08-03 18:01:40 -070010449 /**
10450 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10451 *
10452 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10453 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010454 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010455 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010456 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010457 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010458 mConnectivityDiagnosticsCallbacks.entrySet()) {
10459 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10460 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010461
James Mattis64b8b0f2020-11-24 17:40:49 -080010462 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010463 if (!nai.satisfies(nri.mRequests.get(0))) {
10464 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010465 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010466
10467 // UID for this callback must either be:
10468 // - INVALID_UID (which sends callbacks to all UIDs), or
10469 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10470 // notified as a result)
10471 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10472 continue;
10473 }
10474
10475 if (!checkConnectivityDiagnosticsPermissions(
10476 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10477 continue;
10478 }
10479
10480 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010481 }
10482 return results;
10483 }
10484
Cody Kesting7474f672021-05-11 14:22:40 -070010485 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10486 @NonNull NetworkAgentInfo nai) {
10487 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10488 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10489 }
10490
Cody Kesting160ef392021-05-05 13:17:22 -070010491 private boolean hasLocationPermission(String packageName, int uid) {
10492 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10493 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10494 // call in a try-catch.
10495 try {
10496 if (!mLocationPermissionChecker.checkLocationPermission(
10497 packageName, null /* featureId */, uid, null /* message */)) {
10498 return false;
10499 }
10500 } catch (SecurityException e) {
10501 return false;
10502 }
10503
10504 return true;
10505 }
10506
10507 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10508 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010509 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010510 && virtual.networkCapabilities.getOwnerUid() == uid
10511 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10512 return true;
10513 }
10514 }
10515
10516 return false;
10517 }
10518
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010519 @VisibleForTesting
10520 boolean checkConnectivityDiagnosticsPermissions(
10521 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10522 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10523 return true;
10524 }
10525
Cody Kesting160ef392021-05-05 13:17:22 -070010526 // Administrator UIDs also contains the Owner UID
10527 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10528 if (!CollectionUtils.contains(administratorUids, callbackUid)
10529 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010530 return false;
10531 }
10532
Cody Kesting7474f672021-05-11 14:22:40 -070010533 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10534 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010535 }
10536
Cody Kestingd199a9d2019-12-17 12:55:28 -080010537 @Override
10538 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010539 @NonNull IConnectivityDiagnosticsCallback callback,
10540 @NonNull NetworkRequest request,
10541 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010542 Objects.requireNonNull(callback, "callback must not be null");
10543 Objects.requireNonNull(request, "request must not be null");
10544 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10545
Cody Kesting73708bf2019-12-18 10:57:50 -080010546 if (request.legacyType != TYPE_NONE) {
10547 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10548 + " Please use NetworkCapabilities instead.");
10549 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010550 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010551 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010552
10553 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10554 // and administrator uids to be safe.
10555 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010556 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010557
10558 final NetworkRequest requestWithId =
10559 new NetworkRequest(
10560 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10561
10562 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10563 //
10564 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10565 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10566 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010567 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010568 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010569 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010570
10571 mConnectivityDiagnosticsHandler.sendMessage(
10572 mConnectivityDiagnosticsHandler.obtainMessage(
10573 ConnectivityDiagnosticsHandler
10574 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10575 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010576 }
10577
10578 @Override
10579 public void unregisterConnectivityDiagnosticsCallback(
10580 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010581 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010582 mConnectivityDiagnosticsHandler.sendMessage(
10583 mConnectivityDiagnosticsHandler.obtainMessage(
10584 ConnectivityDiagnosticsHandler
10585 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010586 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010587 0,
10588 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010589 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010590
10591 @Override
10592 public void simulateDataStall(int detectionMethod, long timestampMillis,
10593 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010594 Objects.requireNonNull(network, "network must not be null");
10595 Objects.requireNonNull(extras, "extras must not be null");
10596
paulhu3ffffe72021-09-16 10:15:22 +080010597 enforceAnyPermissionOf(mContext,
10598 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010599 android.Manifest.permission.NETWORK_STACK);
10600 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10601 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010602 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010603 }
10604
10605 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010606 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010607 throw new SecurityException("Data Stall simulation is only possible for network "
10608 + "creators");
10609 }
10610
Cody Kesting652e3ec2020-05-21 12:08:21 -070010611 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10612 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10613 // Data Stall information as a DataStallReportParcelable and passing to
10614 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10615 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010616 final DataStallReportParcelable p = new DataStallReportParcelable();
10617 p.timestampMillis = timestampMillis;
10618 p.detectionMethod = detectionMethod;
10619
10620 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10621 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10622 }
10623 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10624 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10625 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10626 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10627 }
10628
Serik Beketayevec8ad212020-12-07 22:43:07 -080010629 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010630 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010631
lucaslin66f44212021-02-23 01:12:55 +080010632 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10633 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010634 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010635 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010636 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010637 }
lucaslin37a16d92021-01-21 19:48:09 +080010638
10639 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010640 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010641 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010642 nai.clatd.interfaceLinkStateChanged(iface, up);
10643 }
10644 }
10645
10646 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010647 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010648 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010649 nai.clatd.interfaceRemoved(iface);
10650 }
lucaslin66f44212021-02-23 01:12:55 +080010651 }
10652 }
10653
lucaslin1a8b4c62021-01-21 02:02:55 +080010654 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10655
10656 /**
10657 * Class used for updating network activity tracking with netd and notify network activity
10658 * changes.
10659 */
10660 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010661 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010662 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010663 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010664 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10665 new RemoteCallbackList<>();
10666 // Indicate the current system default network activity is active or not.
10667 @GuardedBy("mActiveIdleTimers")
10668 private boolean mNetworkActive;
10669 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010670 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010671 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010672
Chalard Jean46bfbf02022-02-02 00:56:25 +090010673 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010674 public final int timeout;
10675 public final int transportType;
10676
10677 IdleTimerParams(int timeout, int transport) {
10678 this.timeout = timeout;
10679 this.transportType = transport;
10680 }
10681 }
10682
10683 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010684 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010685 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010686 mNetd = netd;
10687 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010688 }
10689
lucaslin66f44212021-02-23 01:12:55 +080010690 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10691 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10692 synchronized (mActiveIdleTimers) {
10693 mNetworkActive = active;
10694 // If there are no idle timers, it means that system is not monitoring
10695 // activity, so the system default network for those default network
10696 // unspecified apps is always considered active.
10697 //
10698 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10699 // any network activity change event. Whenever this event is received,
10700 // the mActiveIdleTimers should be always not empty. The legacy behavior
10701 // is no-op. Remove to refer to mNetworkActive only.
10702 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10703 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10704 }
10705 }
10706 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010707
lucaslin1193a5d2021-01-21 02:04:15 +080010708 // The network activity should only be updated from ConnectivityService handler thread
10709 // when mActiveIdleTimers lock is held.
10710 @GuardedBy("mActiveIdleTimers")
10711 private void reportNetworkActive() {
10712 final int length = mNetworkActivityListeners.beginBroadcast();
10713 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10714 try {
10715 for (int i = 0; i < length; i++) {
10716 try {
10717 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10718 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010719 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010720 }
10721 }
10722 } finally {
10723 mNetworkActivityListeners.finishBroadcast();
10724 }
10725 }
10726
10727 @GuardedBy("mActiveIdleTimers")
10728 public void handleReportNetworkActivity() {
10729 synchronized (mActiveIdleTimers) {
10730 reportNetworkActive();
10731 }
10732 }
10733
lucaslin1a8b4c62021-01-21 02:02:55 +080010734 // This is deprecated and only to support legacy use cases.
10735 private int transportTypeToLegacyType(int type) {
10736 switch (type) {
10737 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010738 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010739 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010740 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010741 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010742 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010743 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010744 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010745 default:
10746 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10747 }
10748 return ConnectivityManager.TYPE_NONE;
10749 }
10750
10751 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10752 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10753 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10754 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10755 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10756 final long ident = Binder.clearCallingIdentity();
10757 try {
10758 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10759 RECEIVE_DATA_ACTIVITY_CHANGE,
10760 null /* resultReceiver */,
10761 null /* scheduler */,
10762 0 /* initialCode */,
10763 null /* initialData */,
10764 null /* initialExtra */);
10765 } finally {
10766 Binder.restoreCallingIdentity(ident);
10767 }
10768 }
10769
10770 /**
10771 * Setup data activity tracking for the given network.
10772 *
10773 * Every {@code setupDataActivityTracking} should be paired with a
10774 * {@link #removeDataActivityTracking} for cleanup.
10775 */
10776 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10777 final String iface = networkAgent.linkProperties.getInterfaceName();
10778
10779 final int timeout;
10780 final int type;
10781
10782 if (networkAgent.networkCapabilities.hasTransport(
10783 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10784 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010785 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010786 10);
10787 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10788 } else if (networkAgent.networkCapabilities.hasTransport(
10789 NetworkCapabilities.TRANSPORT_WIFI)) {
10790 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010791 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010792 15);
10793 type = NetworkCapabilities.TRANSPORT_WIFI;
10794 } else {
10795 return; // do not track any other networks
10796 }
10797
lucaslinb961efc2021-01-21 02:03:17 +080010798 updateRadioPowerState(true /* isActive */, type);
10799
lucaslin1a8b4c62021-01-21 02:02:55 +080010800 if (timeout > 0 && iface != null) {
10801 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010802 synchronized (mActiveIdleTimers) {
10803 // Networks start up.
10804 mNetworkActive = true;
10805 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10806 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10807 reportNetworkActive();
10808 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010809 } catch (Exception e) {
10810 // You shall not crash!
10811 loge("Exception in setupDataActivityTracking " + e);
10812 }
10813 }
10814 }
10815
10816 /**
10817 * Remove data activity tracking when network disconnects.
10818 */
10819 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10820 final String iface = networkAgent.linkProperties.getInterfaceName();
10821 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10822
lucaslinb961efc2021-01-21 02:03:17 +080010823 if (iface == null) return;
10824
10825 final int type;
10826 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10827 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10828 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10829 type = NetworkCapabilities.TRANSPORT_WIFI;
10830 } else {
10831 return; // do not track any other networks
10832 }
10833
10834 try {
10835 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010836 synchronized (mActiveIdleTimers) {
10837 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10838 // The call fails silently if no idle timer setup for this interface
10839 mNetd.idletimerRemoveInterface(iface, params.timeout,
10840 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010841 }
lucaslinb961efc2021-01-21 02:03:17 +080010842 } catch (Exception e) {
10843 // You shall not crash!
10844 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010845 }
10846 }
10847
10848 /**
10849 * Update data activity tracking when network state is updated.
10850 */
10851 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10852 NetworkAgentInfo oldNetwork) {
10853 if (newNetwork != null) {
10854 setupDataActivityTracking(newNetwork);
10855 }
10856 if (oldNetwork != null) {
10857 removeDataActivityTracking(oldNetwork);
10858 }
10859 }
lucaslinb961efc2021-01-21 02:03:17 +080010860
10861 private void updateRadioPowerState(boolean isActive, int transportType) {
10862 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10863 switch (transportType) {
10864 case NetworkCapabilities.TRANSPORT_CELLULAR:
10865 bs.reportMobileRadioPowerState(isActive, NO_UID);
10866 break;
10867 case NetworkCapabilities.TRANSPORT_WIFI:
10868 bs.reportWifiRadioPowerState(isActive, NO_UID);
10869 break;
10870 default:
10871 logw("Untracked transport type:" + transportType);
10872 }
10873 }
lucaslin1193a5d2021-01-21 02:04:15 +080010874
10875 public boolean isDefaultNetworkActive() {
10876 synchronized (mActiveIdleTimers) {
10877 // If there are no idle timers, it means that system is not monitoring activity,
10878 // so the default network is always considered active.
10879 //
10880 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10881 // tracking is disabled (negative idle timer value configured), or no active default
10882 // network. In the latter case, this reports active but it should report inactive.
10883 return mNetworkActive || mActiveIdleTimers.isEmpty();
10884 }
10885 }
10886
10887 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10888 mNetworkActivityListeners.register(l);
10889 }
10890
10891 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10892 mNetworkActivityListeners.unregister(l);
10893 }
lucaslin012f7a12021-01-21 02:04:35 +080010894
10895 public void dump(IndentingPrintWriter pw) {
10896 synchronized (mActiveIdleTimers) {
10897 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10898 pw.println("Idle timers:");
10899 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10900 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10901 final IdleTimerParams params = ent.getValue();
10902 pw.print(" timeout="); pw.print(params.timeout);
10903 pw.print(" type="); pw.println(params.transportType);
10904 }
10905 }
10906 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010907 }
James Mattis47db0582021-01-01 14:13:35 -080010908
Daniel Brightf9e945b2020-06-15 16:10:01 -070010909 /**
10910 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10911 *
10912 * @param socketInfo the socket information
10913 * @param callback the callback to register
10914 */
10915 @Override
10916 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10917 @NonNull final IQosCallback callback) {
10918 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10919 if (nai == null || nai.networkCapabilities == null) {
10920 try {
10921 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10922 } catch (final RemoteException ex) {
10923 loge("registerQosCallbackInternal: RemoteException", ex);
10924 }
10925 return;
10926 }
10927 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10928 }
10929
10930 /**
10931 * Register a {@link IQosCallback} with base {@link QosFilter}.
10932 *
10933 * @param filter the filter to register
10934 * @param callback the callback to register
10935 * @param nai the agent information related to the filter's network
10936 */
10937 @VisibleForTesting
10938 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10939 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010940 Objects.requireNonNull(filter, "filter must be non-null");
10941 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010942
10943 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010944 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10945 // on this network is unregistered when the app loses permission or b) no QoS
10946 // callbacks are sent for restricted networks unless the app currently has permission
10947 // to access restricted networks.
10948 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010949 }
10950 mQosCallbackTracker.registerCallback(callback, filter, nai);
10951 }
10952
10953 /**
10954 * Unregisters the given callback.
10955 *
10956 * @param callback the callback to unregister
10957 */
10958 @Override
10959 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010960 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010961 mQosCallbackTracker.unregisterCallback(callback);
10962 }
James Mattis47db0582021-01-01 14:13:35 -080010963
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010964 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10965 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10966 // Enterprise device can be fully managed like device owner and such use case
10967 // also should be supported. Calling app check for work profile and fully managed device
10968 // is already done in DevicePolicyManager.
10969 // This check is an extra caution to be sure device is fully managed or not.
10970 final UserManager um = mContext.getSystemService(UserManager.class);
10971 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
10972 if (um.isManagedProfile(profile.getIdentifier())) {
10973 return true;
10974 }
10975 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
10976 return false;
10977 }
10978
James Mattis45d81842021-01-10 14:24:24 -080010979 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010980 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010981 *
10982 * See the documentation for the individual preferences for a description of the supported
10983 * behaviors.
10984 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010985 * @param profile If the device owner is set, any profile is allowed.
10986 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010987 * @param preferences the list of profile network preferences for the
10988 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010989 * @param listener an optional listener to listen for completion of the operation.
10990 */
10991 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010992 public void setProfileNetworkPreferences(
10993 @NonNull final UserHandle profile,
10994 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010995 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010996 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010997 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010998
10999 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011000 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11001 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11002 .build();
11003 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011004 }
11005
paulhu3ffffe72021-09-16 10:15:22 +080011006 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011007 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011008 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011009 }
11010 if (profile.getIdentifier() < 0) {
11011 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11012 + "UserHandle.CURRENT not supported)");
11013 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011014 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11015 throw new IllegalArgumentException("Profile must be a managed profile "
11016 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011017 }
paulhuaa0743d2021-05-26 21:56:03 +080011018
Chalard Jean0606fc82022-12-14 20:34:43 +090011019 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011020 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011021 for (final ProfileNetworkPreference preference : preferences) {
11022 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011023 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011024 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011025 switch (preference.getPreference()) {
11026 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11027 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011028 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011029 if (preference.getPreferenceEnterpriseId() != 0) {
11030 throw new IllegalArgumentException(
11031 "Invalid enterprise identifier in setProfileNetworkPreferences");
11032 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011033 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011034 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11035 blockingNonEnterprise = true;
11036 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011037 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11038 allowFallback = false;
11039 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011040 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011041 // This code is needed even though there is a check later on,
11042 // because isRangeAlreadyInPreferenceList assumes that every preference
11043 // has a UID list.
11044 if (hasDefaultPreference) {
11045 throw new IllegalArgumentException(
11046 "Default profile preference should not be set along with other "
11047 + "preference");
11048 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011049 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11050 throw new IllegalArgumentException(
11051 "Invalid enterprise identifier in setProfileNetworkPreferences");
11052 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011053 final Set<UidRange> uidRangeSet =
11054 getUidListToBeAppliedForNetworkPreference(profile, preference);
11055 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11056 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11057 } else {
11058 throw new IllegalArgumentException(
11059 "Overlapping uid range in setProfileNetworkPreferences");
11060 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011061 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011062 nc.addEnterpriseId(
11063 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011064 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11065 break;
11066 default:
11067 throw new IllegalArgumentException(
11068 "Invalid preference in setProfileNetworkPreferences");
11069 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011070 preferenceList.add(new ProfileNetworkPreferenceInfo(
11071 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011072 if (hasDefaultPreference && preferenceList.size() > 1) {
11073 throw new IllegalArgumentException(
11074 "Default profile preference should not be set along with other preference");
11075 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011076 }
11077 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011078 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011079 }
11080
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011081 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11082 @NonNull final UserHandle profile,
11083 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11084 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011085 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11086 profileNetworkPreference.getIncludedUids());
11087
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011088 if (uidRangeSet.size() > 0) {
11089 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11090 throw new IllegalArgumentException(
11091 "Allow uid range is outside the uid range of profile.");
11092 }
11093 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011094 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011095 profileNetworkPreference.getExcludedUids());
11096 if (disallowUidRangeSet.size() > 0) {
11097 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11098 throw new IllegalArgumentException(
11099 "disallow uid range is outside the uid range of profile.");
11100 }
11101 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11102 disallowUidRangeSet);
11103 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011104 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011105 uidRangeSet.add(profileUids);
11106 }
11107 }
11108 return uidRangeSet;
11109 }
11110
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011111 private boolean isEnterpriseIdentifierValid(
11112 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011113 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011114 return true;
11115 }
11116 return false;
11117 }
11118
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011119 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011120 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011121 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011122 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011123 // The NRI for a user should contain the request for capabilities.
11124 // If fallback to default network is needed then NRI should include
11125 // the request for the default network. Create an image of it to
11126 // have the correct UIDs in it (also a request can only be part of one NRI, because
11127 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011128 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11129 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011130 if (pref.allowFallback) {
11131 nrs.add(createDefaultInternetRequestForTransport(
11132 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11133 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011134 if (VDBG) {
11135 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11136 pref.capabilities.getUids()));
11137 }
11138
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011139 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011140 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011141 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011142 result.add(nri);
11143 }
11144 return result;
11145 }
11146
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011147 /**
11148 * Compare if the given UID range sets have the same UIDs.
11149 *
11150 */
11151 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011152 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011153 @NonNull Set<UidRange> uidRangeSet) {
11154 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11155 return false;
11156 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011157 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011158 if (UidRangeUtils.doesRangeSetOverlap(
11159 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11160 return true;
11161 }
11162 }
11163 return false;
11164 }
11165
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011166 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011167 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011168 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011169 /*
11170 * handleSetProfileNetworkPreference is always called for single user.
11171 * preferenceList only contains preferences for different uids within the same user
11172 * (enforced by getUidListToBeAppliedForNetworkPreference).
11173 * Clear all the existing preferences for the user before applying new preferences.
11174 *
11175 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011176 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11177 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011178 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11179 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011180
paulhu74128522021-09-28 02:29:03 +000011181 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11182 addPerAppDefaultNetworkRequests(
11183 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011184 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011185
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011186 // Finally, rematch.
11187 rematchAllNetworksAndRequests();
11188
11189 if (null != listener) {
11190 try {
11191 listener.onComplete();
11192 } catch (RemoteException e) {
11193 loge("Listener for setProfileNetworkPreference has died");
11194 }
11195 }
11196 }
11197
paulhu51f77dc2021-06-07 02:34:20 +000011198 @VisibleForTesting
11199 @NonNull
11200 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11201 @NonNull final Set<Integer> uids) {
11202 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11203 if (uids.size() == 0) {
11204 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11205 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11206 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11207 return nris;
11208 }
11209
11210 final List<NetworkRequest> requests = new ArrayList<>();
11211 // The NRI should be comprised of two layers:
11212 // - The request for the mobile network preferred.
11213 // - The request for the default network, for fallback.
11214 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011215 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011216 requests.add(createDefaultInternetRequestForTransport(
11217 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11218 final Set<UidRange> ranges = new ArraySet<>();
11219 for (final int uid : uids) {
11220 ranges.add(new UidRange(uid, uid));
11221 }
11222 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011223 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011224 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011225 return nris;
11226 }
11227
11228 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011229 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011230 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11231 addPerAppDefaultNetworkRequests(
11232 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011233 // Finally, rematch.
11234 rematchAllNetworksAndRequests();
11235 }
11236
Patrick Rohr2857ac42022-01-21 14:58:16 +010011237 private void handleIngressRateLimitChanged() {
11238 final long oldIngressRateLimit = mIngressRateLimit;
11239 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11240 mContext);
11241 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11242 if (canNetworkBeRateLimited(networkAgent)) {
11243 // If rate limit has previously been enabled, remove the old limit first.
11244 if (oldIngressRateLimit >= 0) {
11245 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11246 }
11247 if (mIngressRateLimit >= 0) {
11248 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11249 mIngressRateLimit);
11250 }
11251 }
11252 }
11253 }
11254
11255 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011256 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
11257 if (!SdkLevel.isAtLeastT()) return false;
11258
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011259 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11260 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11261 // internet connectivity can be rate limited.
11262 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11263 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011264 return false;
11265 }
11266
11267 final String iface = networkAgent.linkProperties.getInterfaceName();
11268 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011269 // This may happen in tests, but if there is no interface then there is nothing that
11270 // can be rate limited.
11271 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011272 return false;
11273 }
11274 return true;
11275 }
11276
James Mattis45d81842021-01-10 14:24:24 -080011277 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011278 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11279 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011280 }
11281
11282 /**
11283 * Used by automotive devices to set the network preferences used to direct traffic at an
11284 * application level as per the given OemNetworkPreferences. An example use-case would be an
11285 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11286 * vehicle via a particular network.
11287 *
11288 * Calling this will overwrite the existing preference.
11289 *
James Mattisda32cfe2021-01-26 16:23:52 -080011290 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011291 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011292 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011293 */
James Mattis47db0582021-01-01 14:13:35 -080011294 @Override
James Mattis45d81842021-01-10 14:24:24 -080011295 public void setOemNetworkPreference(
11296 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011297 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011298
James Mattisfa270db2021-05-31 17:11:10 -070011299 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11300 // Only bypass the permission/device checks if this is a valid test request.
11301 if (isValidTestOemNetworkPreference(preference)) {
11302 enforceManageTestNetworksPermission();
11303 } else {
11304 enforceAutomotiveDevice();
11305 enforceOemNetworkPreferencesPermission();
11306 validateOemNetworkPreferences(preference);
11307 }
James Mattis45d81842021-01-10 14:24:24 -080011308
James Mattis45d81842021-01-10 14:24:24 -080011309 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11310 new Pair<>(preference, listener)));
11311 }
11312
James Mattisfa270db2021-05-31 17:11:10 -070011313 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011314 * Sets the specified UIDs to get/receive the VPN as the only default network.
11315 *
11316 * Calling this will overwrite the existing network preference for this session, and the
11317 * specified UIDs won't get any default network when no VPN is connected.
11318 *
11319 * @param session The VPN session which manages the passed UIDs.
11320 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11321 * setting for this session if the array is empty. Null is not allowed, the
11322 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11323 * @hide
11324 */
11325 @Override
11326 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11327 Objects.requireNonNull(ranges);
11328 enforceNetworkStackOrSettingsPermission();
11329 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11330 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11331 throw new IllegalArgumentException(
11332 "setVpnNetworkPreference: Passed UID ranges overlap");
11333 }
11334
11335 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11336 new VpnNetworkPreferenceInfo(session,
11337 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11338 }
11339
11340 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11341 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11342
11343 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11344 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11345
11346 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11347 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11348 // Finally, rematch.
11349 rematchAllNetworksAndRequests();
11350 }
11351
11352 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11353 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11354 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11355 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11356 final List<NetworkRequest> requests = new ArrayList<>();
11357 // Request VPN only, so other networks won't be the fallback options when VPN is not
11358 // connected temporarily.
11359 requests.add(createVpnRequest());
11360 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11361 setNetworkRequestUids(requests, uidRanges);
11362 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11363 }
11364 return nris;
11365 }
11366
11367 /**
James Mattisfa270db2021-05-31 17:11:10 -070011368 * Check the validity of an OEM network preference to be used for testing purposes.
11369 * @param preference the preference to validate
11370 * @return true if this is a valid OEM network preference test request.
11371 */
11372 private boolean isValidTestOemNetworkPreference(
11373 @NonNull final OemNetworkPreferences preference) {
11374 // Allow for clearing of an existing OemNetworkPreference used for testing.
11375 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11376 // changes after this check is complete. This is an unlikely scenario as calling of this API
11377 // is controlled by the OEM therefore the added complexity is not worth adding given those
11378 // circumstances. That said, it is an edge case to be aware of hence this comment.
11379 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11380 && isTestOemNetworkPreference(mOemNetworkPreferences);
11381 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11382 }
11383
11384 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11385 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11386 return prefMap.size() == 1
11387 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11388 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11389 }
11390
James Mattis45d81842021-01-10 14:24:24 -080011391 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11392 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11393 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011394 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11395 throw new IllegalArgumentException(
11396 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11397 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011398 }
11399 }
11400 }
11401
11402 private void handleSetOemNetworkPreference(
11403 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011404 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011405 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11406 if (DBG) {
11407 log("set OEM network preferences :" + preference.toString());
11408 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011409
James Mattiscb1e0362021-04-06 17:07:42 -070011410 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011411 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11412 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11413 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011414 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011415
11416 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011417 try {
11418 listener.onComplete();
11419 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011420 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011421 }
James Mattis45d81842021-01-10 14:24:24 -080011422 }
11423 }
11424
paulhu74128522021-09-28 02:29:03 +000011425 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011426 // Skip the requests which are set by other network preference. Because the uid range rules
11427 // should stay in netd.
11428 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011429 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011430 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011431 }
11432
James Mattis3ce3d3c2021-02-09 18:18:28 -080011433 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11434 ensureRunningOnConnectivityServiceThread();
11435 mDefaultNetworkRequests.addAll(nris);
11436 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11437 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011438 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011439 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11440 nrisToRegister.addAll(
11441 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11442 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011443 }
11444
11445 /**
11446 * All current requests that are tracking the default network need to be assessed as to whether
11447 * or not the current set of per-application default requests will be changing their default
11448 * network. If so, those requests will need to be updated so that they will send callbacks for
11449 * default network changes at the appropriate time. Additionally, those requests tracking the
11450 * default that were previously updated by this flow will need to be reassessed.
11451 * @return the nris which will need to be updated.
11452 */
11453 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11454 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11455 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11456 // same nri in the map's values for each of its NetworkRequest objects.
11457 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011458 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011459 // Include this nri if it is currently being tracked.
11460 if (isPerAppTrackedNri(nri)) {
11461 defaultCallbackRequests.add(nri);
11462 continue;
11463 }
11464 // We only track callbacks for requests tracking the default.
11465 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11466 continue;
11467 }
11468 // Include this nri if it will be tracked by the new per-app default requests.
11469 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011470 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011471 if (isNriGoingToBeTracked) {
11472 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011473 }
11474 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011475 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011476 }
11477
James Mattis3ce3d3c2021-02-09 18:18:28 -080011478 /**
11479 * Create nris for those network requests that are currently tracking the default network that
11480 * are being controlled by a per-application default.
11481 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11482 * foundation when creating the nri. Important items include the calling uid's original
11483 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11484 * requests are assumed to have already been validated as needing to be updated.
11485 * @return the Set of nris to use when registering network requests.
11486 */
11487 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11488 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11489 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11490 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11491 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011492 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011493
Chalard Jean9473c982021-07-29 20:03:04 +090011494 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011495 if (trackingNri == mDefaultRequest) {
11496 callbackRequestsToRegister.add(new NetworkRequestInfo(
11497 callbackRequest,
11498 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11499 continue;
11500 }
11501
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011502 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011503 callbackRequestsToRegister.add(new NetworkRequestInfo(
11504 callbackRequest,
11505 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011506 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011507 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011508 }
11509 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011510 }
11511
Chalard Jean17215832021-03-01 14:06:28 +090011512 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11513 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011514 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011515 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011516 }
11517 }
11518
James Mattis45d81842021-01-10 14:24:24 -080011519 /**
11520 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11521 */
11522 @VisibleForTesting
11523 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011524 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011525 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011526 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011527 final SparseArray<Set<Integer>> uids =
11528 createUidsFromOemNetworkPreferences(preference);
11529 for (int i = 0; i < uids.size(); i++) {
11530 final int key = uids.keyAt(i);
11531 final Set<Integer> value = uids.valueAt(i);
11532 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11533 // No need to add an nri without any requests.
11534 if (0 == nri.mRequests.size()) {
11535 continue;
11536 }
11537 nris.add(nri);
11538 }
11539
11540 return nris;
11541 }
11542
11543 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11544 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011545 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011546 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011547 final List<UserHandle> users =
11548 mContext.getSystemService(UserManager.class).getUserHandles(true);
11549 if (null == users || users.size() == 0) {
11550 if (VDBG || DDBG) {
11551 log("No users currently available for setting the OEM network preference.");
11552 }
James Mattisb6b6a432021-06-01 22:30:36 -070011553 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011554 }
James Mattis45d81842021-01-10 14:24:24 -080011555 for (final Map.Entry<String, Integer> entry :
11556 preference.getNetworkPreferences().entrySet()) {
11557 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011558 // Add the rules for all users as this policy is device wide.
11559 for (final UserHandle user : users) {
11560 try {
11561 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11562 if (!prefToUids.contains(pref)) {
11563 prefToUids.put(pref, new ArraySet<>());
11564 }
11565 prefToUids.get(pref).add(uid);
11566 } catch (PackageManager.NameNotFoundException e) {
11567 // Although this may seem like an error scenario, it is ok that uninstalled
11568 // packages are sent on a network preference as the system will watch for
11569 // package installations associated with this network preference and update
11570 // accordingly. This is done to minimize race conditions on app install.
11571 continue;
James Mattis45d81842021-01-10 14:24:24 -080011572 }
James Mattis45d81842021-01-10 14:24:24 -080011573 }
11574 }
James Mattisb6b6a432021-06-01 22:30:36 -070011575 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011576 }
11577
11578 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11579 @OemNetworkPreferences.OemNetworkPreference final int preference,
11580 @NonNull final Set<Integer> uids) {
11581 final List<NetworkRequest> requests = new ArrayList<>();
11582 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11583 switch (preference) {
11584 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11585 requests.add(createUnmeteredNetworkRequest());
11586 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011587 requests.add(createDefaultInternetRequestForTransport(
11588 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011589 break;
11590 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11591 requests.add(createUnmeteredNetworkRequest());
11592 requests.add(createOemPaidNetworkRequest());
11593 break;
11594 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11595 requests.add(createOemPaidNetworkRequest());
11596 break;
11597 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11598 requests.add(createOemPrivateNetworkRequest());
11599 break;
James Mattisfa270db2021-05-31 17:11:10 -070011600 case OEM_NETWORK_PREFERENCE_TEST:
11601 requests.add(createUnmeteredNetworkRequest());
11602 requests.add(createTestNetworkRequest());
11603 requests.add(createDefaultRequest());
11604 break;
11605 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11606 requests.add(createTestNetworkRequest());
11607 break;
James Mattis45d81842021-01-10 14:24:24 -080011608 default:
11609 // This should never happen.
11610 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11611 + " called with invalid preference of " + preference);
11612 }
11613
James Mattisfa270db2021-05-31 17:11:10 -070011614 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011615 for (final int uid : uids) {
11616 ranges.add(new UidRange(uid, uid));
11617 }
11618 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011619 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011620 }
11621
11622 private NetworkRequest createUnmeteredNetworkRequest() {
11623 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11624 .addCapability(NET_CAPABILITY_NOT_METERED)
11625 .addCapability(NET_CAPABILITY_VALIDATED);
11626 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11627 }
11628
11629 private NetworkRequest createOemPaidNetworkRequest() {
11630 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11631 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11632 .addCapability(NET_CAPABILITY_OEM_PAID)
11633 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11634 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11635 }
11636
11637 private NetworkRequest createOemPrivateNetworkRequest() {
11638 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11639 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11640 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11641 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11642 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11643 }
11644
11645 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011646 final NetworkCapabilities netcap = new NetworkCapabilities();
11647 netcap.addCapability(NET_CAPABILITY_INTERNET);
11648 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11649 return netcap;
11650 }
11651
11652 private NetworkRequest createTestNetworkRequest() {
11653 final NetworkCapabilities netcap = new NetworkCapabilities();
11654 netcap.clearAll();
11655 netcap.addTransportType(TRANSPORT_TEST);
11656 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011657 }
James Mattis47db0582021-01-01 14:13:35 -080011658 }
markchien738ad912021-12-09 18:15:45 +080011659
11660 @Override
11661 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11662 enforceNetworkStackOrSettingsPermission();
11663
11664 try {
11665 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011666 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011667 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011668 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011669 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011670 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011671 throw new IllegalStateException(e);
11672 }
11673 }
11674
11675 @Override
11676 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11677 enforceNetworkStackOrSettingsPermission();
11678
11679 try {
11680 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011681 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011682 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011683 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011684 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011685 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011686 throw new IllegalStateException(e);
11687 }
11688 }
markchiene1561fa2021-12-09 22:00:56 +080011689
11690 @Override
markchien3c04e662022-03-22 16:29:56 +080011691 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011692 enforceNetworkStackOrSettingsPermission();
11693
markchien3c04e662022-03-22 16:29:56 +080011694 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11695 int firewallRule = getFirewallRuleType(chain, rule);
11696
11697 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11698 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11699 }
11700
markchiene1561fa2021-12-09 22:00:56 +080011701 try {
markchien3c04e662022-03-22 16:29:56 +080011702 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011703 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011704 throw new IllegalStateException(e);
11705 }
11706 }
markchien98a6f952022-01-13 23:43:53 +080011707
markchien3c04e662022-03-22 16:29:56 +080011708 private int getFirewallRuleType(int chain, int rule) {
11709 final int defaultRule;
11710 switch (chain) {
11711 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011712 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11713 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011714 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011715 defaultRule = FIREWALL_RULE_ALLOW;
11716 break;
11717 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11718 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11719 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11720 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11721 defaultRule = FIREWALL_RULE_DENY;
11722 break;
11723 default:
11724 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11725 }
11726 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11727
11728 return rule;
11729 }
11730
markchien98a6f952022-01-13 23:43:53 +080011731 @Override
11732 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11733 enforceNetworkStackOrSettingsPermission();
11734
11735 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011736 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011737 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011738 throw new IllegalStateException(e);
11739 }
11740 }
11741
markchien00a0bed2022-01-13 23:46:13 +080011742 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011743 public boolean getFirewallChainEnabled(final int chain) {
11744 enforceNetworkStackOrSettingsPermission();
11745
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011746 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011747 }
11748
11749 @Override
markchien00a0bed2022-01-13 23:46:13 +080011750 public void replaceFirewallChain(final int chain, final int[] uids) {
11751 enforceNetworkStackOrSettingsPermission();
11752
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011753 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011754 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080011755
11756 @Override
11757 public IBinder getCompanionDeviceManagerProxyService() {
11758 enforceNetworkStackPermission(mContext);
11759 return mCdmps;
11760 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011761}