blob: e969cd656f1c4d5d9c82b9463f504ab8134d26b9 [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;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900116import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800117import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700118import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800119import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800120import android.content.ContentResolver;
121import android.content.Context;
122import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700123import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800124import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900125import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700126import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900127import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900128import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700129import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800130import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800131import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900133import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800134import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900135import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900136import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800137import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900138import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800139import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700140import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900141import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800142import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800143import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800144import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800145import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800146import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900147import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900148import android.net.INetworkMonitor;
149import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900150import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900151import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700152import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800153import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900154import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900155import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900156import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800157import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100158import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800159import android.net.NativeNetworkConfig;
160import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800161import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700162import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700163import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900164import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700165import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800166import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700167import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900168import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900169import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000170import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900171import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700172import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900173import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700174import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900175import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700176import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800177import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900178import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700179import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000180import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800181import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900182import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800183import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400184import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700185import android.net.QosCallbackException;
186import android.net.QosFilter;
187import android.net.QosSocketFilter;
188import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700189import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800190import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800191import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800192import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900193import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400194import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800195import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800196import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400197import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800198import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900199import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900200import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900201import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900202import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800203import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900204import android.net.networkstack.ModuleNetworkStackClient;
205import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900206import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800207import android.net.resolv.aidl.DnsHealthEventParcel;
208import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
209import android.net.resolv.aidl.Nat64PrefixEventParcel;
210import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900211import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900212import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800213import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800215import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700216import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000217import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800218import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700219import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700220import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800221import android.os.Looper;
222import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700223import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700224import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900225import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800226import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700227import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700228import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800229import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700230import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900231import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900232import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700233import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700234import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400235import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800236import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900237import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700238import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700239import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700240import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800241import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900242import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000243import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600244import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900245import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700246import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700247import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800248
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800249import androidx.annotation.RequiresApi;
250
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900251import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400252import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400253import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700254import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900255import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800256import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900257import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800258import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000259import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900260import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900261import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900262import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100263import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900264import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
265import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900266import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800267import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800268import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100269import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000270import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800271import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
272import com.android.networkstack.apishim.ConstantsShim;
273import com.android.networkstack.apishim.common.BroadcastOptionsShim;
274import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900275import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900276import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000277import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900278import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800279import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800280import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900281import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900282import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500283import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700284import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900285import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900286import com.android.server.connectivity.InvalidTagException;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000287import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100288import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700289import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900290import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700291import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600292import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900293import com.android.server.connectivity.NetworkNotificationManager;
294import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900295import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900296import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900297import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700298import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900299import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900300import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700301import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800302import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000303import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800304import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600305
Josh Gao461a1222020-06-16 15:58:11 -0700306import libcore.io.IoUtils;
307
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900308import org.xmlpull.v1.XmlPullParserException;
309
The Android Open Source Project28527d22009-03-03 19:31:44 -0800310import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100311import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800312import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900313import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700314import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700315import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900316import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700317import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700318import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700319import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700320import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800321import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900322import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800323import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700324import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700325import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700326import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700327import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900328import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700329import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900330import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600331import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900332import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600333import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900334import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800335
336/**
337 * @hide
338 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800339public class ConnectivityService extends IConnectivityManager.Stub
340 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900341 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800342
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900343 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900344 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900345 private static final String NETWORK_ARG = "networks";
346 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800347 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900348
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900349 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900350 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
351 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800352
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900353 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700354
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100355 /**
356 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
357 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800358 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100359 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
360 * (preferably via runtime resource overlays).
361 */
362 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
363 "http://connectivitycheck.gstatic.com/generate_204";
364
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700365 // TODO: create better separation between radio types and network types
366
Robert Greenwalt2034b912009-08-12 16:08:25 -0700367 // how long to wait before switching back to a radio's default network
368 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
369 // system property that can override the above value
370 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
371 "android.telephony.apn-restore";
372
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900373 // How long to wait before putting up a "This network doesn't have an Internet connection,
374 // connect anyway?" dialog after the user selects a network that doesn't validate.
375 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
376
Chalard Jean5fb43c72022-09-08 19:03:14 +0900377 // How long to wait before considering that a network is bad in the absence of any form
378 // of connectivity (valid, partial, captive portal). If none has been detected after this
379 // delay, the stack considers this network bad, which may affect how it's handled in ranking
380 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900381 // Timeout in case the "actively prefer bad wifi" feature is on
382 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
383 // Timeout in case the "actively prefer bad wifi" feature is off
384 private static final int DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900385
junyulai0ac374f2020-12-14 18:41:52 +0800386 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900387 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
388 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800389 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700390
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800391 // Delimiter used when creating the broadcast delivery group for sending
392 // CONNECTIVITY_ACTION broadcast.
393 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
394
he_won.hwang881307a2022-03-15 21:23:52 +0900395 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900396 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900397
Daniel Brightf9e945b2020-06-15 16:10:01 -0700398 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900399 @VisibleForTesting
400 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700401
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900402 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700403 @VisibleForTesting
404 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900405
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900406 @VisibleForTesting
407 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800408 @VisibleForTesting
409 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900410 // True if the cell radio of the device is capable of time-sharing.
411 @VisibleForTesting
412 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900413
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800414 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800415 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800416 private final int mReleasePendingIntentDelayMs;
417
Chalard Jean46bfbf02022-02-02 00:56:25 +0900418 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900419
Motomu Utsumif360aa62023-01-30 17:52:20 +0900420 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700421
Chalard Jean9473c982021-07-29 20:03:04 +0900422 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800423 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700424 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800425 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700426
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900427 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700428
junyulaif2c67e42018-08-07 19:50:45 +0800429 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000430 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
431 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800432 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900433 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800434
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900435 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900436 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000437 // The Context is created for UserHandle.ALL.
438 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900439 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900440 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700441 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700442 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800443
Chenbo Feng15416292018-11-08 17:36:21 -0800444 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800445 protected IDnsResolver mDnsResolver;
446 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800447 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700448 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900449 private final NetworkStatsManager mStatsManager;
450 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800451 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700452
Benedict Wong493e04b2018-11-09 14:45:34 -0800453 /**
454 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
455 * instances.
456 */
457 @GuardedBy("mTNSLock")
458 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800459 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800460
461 private final Object mTNSLock = new Object();
462
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700463 private String mCurrentTcpBufferSizes;
464
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900465 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800466 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900467
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500468 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400469 // Tear down networks that have no chance (e.g. even if validated) of becoming
470 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500471 // all networks have been rematched against all NetworkRequests.
472 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400473 // Don't reap networks. This should be passed when some networks have not yet been
474 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500475 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900476 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500477
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900478 private enum UnneededFor {
479 LINGER, // Determine whether this network is unneeded and should be lingered.
480 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
481 }
482
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700483 /**
paulhuaa0743d2021-05-26 21:56:03 +0800484 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800485 * should have priority. The order is passed to netd which will use it together
486 * with UID ranges to generate the corresponding IP rule. This serves to
487 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800488 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800489 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000490 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800491 *
paulhu48291862021-07-14 14:53:57 +0800492 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
493 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800494 */
paulhu48291862021-07-14 14:53:57 +0800495 // Used when sending to netd to code for "no order".
496 static final int PREFERENCE_ORDER_NONE = 0;
497 // Order for requests that don't code for a per-app preference. As it is
498 // out of the valid range, the corresponding order should be
499 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800500 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800501 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800502 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800503 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
504 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800505 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800506 static final int PREFERENCE_ORDER_OEM = 10;
507 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800508 // See {@link #setProfileNetworkPreference}.
509 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800510 static final int PREFERENCE_ORDER_PROFILE = 20;
511 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800512 // better scores are connected.
513 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800514 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800515 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900516 // Preference order that signifies the network shouldn't be set as a default network for
517 // the UIDs, only give them access to it. TODO : replace this with a boolean
518 // in NativeUidRangeConfig
519 @VisibleForTesting
520 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
521 // Bound for the lowest valid preference order.
522 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800523
524 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700525 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700526 * from one net to another. Clear happens when we get a new
527 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
528 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700529 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700530 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700531
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700532 /**
533 * used internally to reload global proxy settings
534 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700535 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700536
Robert Greenwalt34848c02011-03-25 13:09:25 -0700537 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400538 * PAC manager has received new port.
539 */
540 private static final int EVENT_PROXY_HAS_CHANGED = 16;
541
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700542 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900543 * used internally when registering NetworkProviders
544 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700545 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900546 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700547
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700548 /**
549 * used internally when registering NetworkAgents
550 * obj = Messenger
551 */
552 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
553
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700554 /**
555 * used to add a network request
556 * includes a NetworkRequestInfo
557 */
558 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
559
560 /**
561 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900562 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700563 * cancel it.
564 * includes a NetworkRequestInfo
565 */
566 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
567
568 /**
569 * used to add a network listener - no request
570 * includes a NetworkRequestInfo
571 */
572 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
573
574 /**
575 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400576 * arg1 = UID of caller
577 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700578 */
579 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
580
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700581 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900582 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700583 * obj = Messenger
584 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900585 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700586
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700587 /**
588 * used internally to expire a wakelock when transitioning
589 * from one net to another. Expire happens when we fail to find
590 * a new network (typically after 1 minute) -
591 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
592 * a replacement network.
593 */
594 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
595
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700596 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800597 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400598 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800599 */
600 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
601
602 /**
603 * used to remove a pending intent and its associated network request.
604 * arg1 = UID of caller
605 * obj = PendingIntent
606 */
607 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
608
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900609 /**
610 * used to specify whether a network should be used even if unvalidated.
611 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
612 * arg2 = whether to remember this choice in the future (1 or 0)
613 * obj = network
614 */
615 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
616
617 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700618 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900619 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700620 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900621
Paul Jensenc8873fc2015-06-17 14:15:39 -0400622 /**
623 * used to add a network listener with a pending intent
624 * obj = NetworkRequestInfo
625 */
626 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
627
Hugo Benichid6b510a2017-04-06 17:22:18 +0900628 /**
629 * used to specify whether a network should not be penalized when it becomes unvalidated.
630 */
631 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
632
633 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700634 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900635 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700636 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900637
Erik Kline31b4a9e2018-01-11 21:07:29 +0900638 // Handle changes in Private DNS settings.
639 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
640
dalyk1720e542018-03-05 12:42:22 -0500641 // Handle private DNS validation status updates.
642 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
643
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900644 /**
645 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
646 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800647 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
648 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
649 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900650 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900651 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900652
653 /**
654 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
655 * config was resolved.
656 * obj = PrivateDnsConfig
657 * arg2 = netid
658 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900659 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900660
661 /**
662 * Request ConnectivityService display provisioning notification.
663 * arg1 = Whether to make the notification visible.
664 * arg2 = NetID.
665 * obj = Intent to be launched when notification selected by user, null if !arg1.
666 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900667 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900668
669 /**
lucaslin2240ef62019-03-12 13:08:03 +0800670 * Used to specify whether a network should be used even if connectivity is partial.
671 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
672 * false)
673 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
674 * obj = network
675 */
lucaslin444d43a2020-02-20 16:56:59 +0800676 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800677
678 /**
lucasline117e2e2019-10-22 18:27:33 +0800679 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
680 * Both of the arguments are bitmasks, and the value of bits come from
681 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900682 * arg1 = unused
683 * arg2 = netId
684 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800685 */
lucaslin444d43a2020-02-20 16:56:59 +0800686 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800687
688 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900689 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
690 * arg1 = unused
691 * arg2 = netId
692 * obj = captive portal data
693 */
lucaslin444d43a2020-02-20 16:56:59 +0800694 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900695
696 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900697 * Used by setRequireVpnForUids.
698 * arg1 = whether the specified UID ranges are required to use a VPN.
699 * obj = Array of UidRange objects.
700 */
701 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
702
703 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900704 * Used internally when setting the default networks for OemNetworkPreferences.
705 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800706 */
707 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
708
709 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800710 * Used to indicate the system default network becomes active.
711 */
712 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
713
714 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900715 * Used internally when setting a network preference for a user profile.
716 * obj = Pair<ProfileNetworkPreference, Listener>
717 */
718 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
719
720 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000721 * Event to specify that reasons for why an uid is blocked changed.
722 * arg1 = uid
723 * arg2 = blockedReasons
724 */
725 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
726
727 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900728 * Event to register a new network offer
729 * obj = NetworkOffer
730 */
731 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
732
733 /**
734 * Event to unregister an existing network offer
735 * obj = INetworkOfferCallback
736 */
737 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
738
739 /**
paulhu51f77dc2021-06-07 02:34:20 +0000740 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
741 */
742 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
743
744 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800745 * Event to set temporary allow bad wifi within a limited time to override
746 * {@code config_networkAvoidBadWifi}.
747 */
748 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
749
750 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100751 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
752 */
753 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
754
755 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900756 * The initial evaluation period is over for this network.
757 *
758 * If no form of connectivity has been found on this network (valid, partial, captive portal)
759 * then the stack will now consider it to have been determined bad.
760 */
761 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
762
763 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000764 * Used internally when the user does not want the network from captive portal app.
765 * obj = Network
766 */
767 private static final int EVENT_USER_DOES_NOT_WANT = 58;
768
769 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000770 * Event to set VPN as preferred network for specific apps.
771 * obj = VpnNetworkPreferenceInfo
772 */
773 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
774
775 /**
chiachangwange0192a72023-02-06 13:25:01 +0000776 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
777 */
778 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
779
780 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900781 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
782 * should be shown.
783 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900784 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900785
786 /**
787 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
788 * should be hidden.
789 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900790 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900791
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800792 /**
793 * The maximum alive time to allow bad wifi configuration for testing.
794 */
795 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
796
Patrick Rohr2857ac42022-01-21 14:58:16 +0100797 /**
chiachangwange0192a72023-02-06 13:25:01 +0000798 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
799 * testing.
800 */
801 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
802
803 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100804 * The priority of the tc police rate limiter -- smaller value is higher priority.
805 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
806 */
807 private static final short TC_PRIO_POLICE = 1;
808
809 /**
810 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
811 */
812 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700813 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100814
Hugo Benichi47011212017-03-30 10:46:05 +0900815 private static String eventName(int what) {
816 return sMagicDecoderRing.get(what, Integer.toString(what));
817 }
818
paulhua10d8212020-11-10 15:32:56 +0800819 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900820 final DnsResolverServiceManager dsm = context.getSystemService(
821 DnsResolverServiceManager.class);
822 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800823 }
824
Cody Kesting73708bf2019-12-18 10:57:50 -0800825 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900826 @VisibleForTesting
827 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700828 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700829 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700830 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700831 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800832 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
833 @VisibleForTesting
834 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
835
Erik Kline32120082017-12-13 19:40:49 +0900836 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900837 @VisibleForTesting
838 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700839
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400840 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800841 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400842
Chalard Jean46bfbf02022-02-02 00:56:25 +0900843 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800844 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700845
Chalard Jean5d70ba42018-06-07 16:44:04 +0900846 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
847 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000848 @VisibleForTesting
849 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400850
Erik Kline05f2b402015-04-30 12:58:40 +0900851 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700852
Chalard Jean46bfbf02022-02-02 00:56:25 +0900853 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400854
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700855 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900856 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700857
Valentin Iftime9fa35092019-09-24 13:32:13 +0200858 private Set<String> mWolSupportedInterfaces;
859
Roshan Pius08c94fb2020-01-16 12:17:17 -0800860 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800861 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800862 private final AppOpsManager mAppOpsManager;
863
864 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400865
chiachangwang3d60bac2023-01-17 14:38:08 +0000866 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900867 private final QosCallbackTracker mQosCallbackTracker;
868 private final NetworkNotificationManager mNotifier;
869 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900870
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700871 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800872 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700873
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900874 // Sequence number for NetworkProvider IDs.
875 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
876 NetworkProvider.FIRST_PROVIDER_ID);
877
Erik Klineedf878b2015-07-09 18:24:03 +0900878 // NetworkRequest activity String log entries.
879 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
880 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
881
Hugo Benichid159fdd2016-07-11 11:05:12 +0900882 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900883 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900884 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
885
Hugo Benichi47011212017-03-30 10:46:05 +0900886 private static final int MAX_WAKELOCK_LOGS = 20;
887 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900888 private int mTotalWakelockAcquisitions = 0;
889 private int mTotalWakelockReleases = 0;
890 private long mTotalWakelockDurationMs = 0;
891 private long mMaxWakelockDurationMs = 0;
892 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900893
Hugo Benichi208c0102016-07-28 17:53:06 +0900894 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900895
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700896 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900897 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700898
Erik Kline95ecfee2016-10-02 18:02:14 +0900899 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900900 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900901
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900902 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800903 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
904 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800905
Patrick Rohr2857ac42022-01-21 14:58:16 +0100906 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
907 // configured via {@link
908 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
909 // Only the handler thread is allowed to access this field.
910 private long mIngressRateLimit = -1;
911
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900912 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
913 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900914 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900915 @GuardedBy("mSelfCertifiedCapabilityCache")
916 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
917 mSelfCertifiedCapabilityCache = new HashMap<>();
918
Robert Greenwalt802c1102014-06-02 15:32:02 -0700919 /**
920 * Implements support for the legacy "one network per network type" model.
921 *
922 * We used to have a static array of NetworkStateTrackers, one for each
923 * network type, but that doesn't work any more now that we can have,
924 * for example, more that one wifi network. This class stores all the
925 * NetworkAgentInfo objects that support a given type, but the legacy
926 * API will only see the first one.
927 *
928 * It serves two main purposes:
929 *
930 * 1. Provide information about "the network for a given type" (since this
931 * API only supports one).
932 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
933 * the first network for a given type changes, or if the default network
934 * changes.
935 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900936 @VisibleForTesting
937 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900938
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900939 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900940 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900941
Robert Greenwalt802c1102014-06-02 15:32:02 -0700942 /**
943 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
944 * Each list holds references to all NetworkAgentInfos that are used to
945 * satisfy requests for that network type.
946 *
947 * This array is built out at startup such that an unsupported network
948 * doesn't get an ArrayList instance, making this a tristate:
949 * unsupported, supported but not active and active.
950 *
951 * The actual lists are populated when we scan the network types that
952 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900953 *
954 * Threading model:
955 * - addSupportedType() is only called in the constructor
956 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
957 * They are therefore not thread-safe with respect to each other.
958 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
959 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900960 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900961 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700962 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900963 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900964 @NonNull
965 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700966
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900967 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
968 // an entry have no timer (equivalent to -1). Lazily loaded.
969 @NonNull
970 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
971
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900972 LegacyTypeTracker(@NonNull ConnectivityService service) {
973 mService = service;
974 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700975 }
976
Chiachang Wang3bc52762021-11-25 14:17:57 +0800977 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
978 // addressed.
979 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900980 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
981 final PackageManager pm = ctx.getPackageManager();
982 if (pm.hasSystemFeature(FEATURE_WIFI)) {
983 addSupportedType(TYPE_WIFI);
984 }
985 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
986 addSupportedType(TYPE_WIFI_P2P);
987 }
988 if (tm.isDataCapable()) {
989 // Telephony does not have granular support for these types: they are either all
990 // supported, or none is supported
991 addSupportedType(TYPE_MOBILE);
992 addSupportedType(TYPE_MOBILE_MMS);
993 addSupportedType(TYPE_MOBILE_SUPL);
994 addSupportedType(TYPE_MOBILE_DUN);
995 addSupportedType(TYPE_MOBILE_HIPRI);
996 addSupportedType(TYPE_MOBILE_FOTA);
997 addSupportedType(TYPE_MOBILE_IMS);
998 addSupportedType(TYPE_MOBILE_CBS);
999 addSupportedType(TYPE_MOBILE_IA);
1000 addSupportedType(TYPE_MOBILE_EMERGENCY);
1001 }
1002 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1003 addSupportedType(TYPE_BLUETOOTH);
1004 }
1005 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1006 // TYPE_PROXY is only used on Wear
1007 addSupportedType(TYPE_PROXY);
1008 }
1009 // Ethernet is often not specified in the configs, although many devices can use it via
1010 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001011 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001012 addSupportedType(TYPE_ETHERNET);
1013 }
1014
1015 // Always add TYPE_VPN as a supported type
1016 addSupportedType(TYPE_VPN);
1017 }
1018
1019 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001020 if (mTypeLists[type] != null) {
1021 throw new IllegalStateException(
1022 "legacy list for type " + type + "already initialized");
1023 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001024 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001025 }
1026
Robert Greenwalt802c1102014-06-02 15:32:02 -07001027 public boolean isTypeSupported(int type) {
1028 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1029 }
1030
1031 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001032 synchronized (mTypeLists) {
1033 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1034 return mTypeLists[type].get(0);
1035 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001036 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001037 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001038 }
1039
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001040 public int getRestoreTimerForType(int type) {
1041 synchronized (mTypeLists) {
1042 if (mRestoreTimers == null) {
1043 mRestoreTimers = loadRestoreTimers();
1044 }
1045 return mRestoreTimers.getOrDefault(type, -1);
1046 }
1047 }
1048
1049 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1050 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001051 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001052 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1053 for (final String config : configs) {
1054 final String[] splits = TextUtils.split(config, ",");
1055 if (splits.length != 2) {
1056 logwtf("Invalid restore timer token count: " + config);
1057 continue;
1058 }
1059 try {
1060 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1061 } catch (NumberFormatException e) {
1062 logwtf("Invalid restore timer number format: " + config, e);
1063 }
1064 }
1065 return ret;
1066 }
1067
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001068 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001069 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001070 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001071 log("Sending " + state
1072 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001073 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001074 }
1075 }
1076
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001077 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1078 // network type, to preserve previous behaviour.
1079 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1080 if (vpnNai != mService.getLegacyLockdownNai()) return;
1081
1082 if (vpnNai.declaredUnderlyingNetworks == null
1083 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1084 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1085 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1086 return;
1087 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001088 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001089 vpnNai.declaredUnderlyingNetworks[0]);
1090 if (underlyingNai == null) return;
1091
1092 final int type = underlyingNai.networkInfo.getType();
1093 final DetailedState state = DetailedState.CONNECTED;
1094 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1095 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1096 }
1097
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001098 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001099 public void add(int type, NetworkAgentInfo nai) {
1100 if (!isTypeSupported(type)) {
1101 return; // Invalid network type.
1102 }
1103 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1104
1105 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1106 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001107 return;
1108 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001109 synchronized (mTypeLists) {
1110 list.add(nai);
1111 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001112
Chalard Jean5b409c72021-02-04 13:12:59 +09001113 // Send a broadcast if this is the first network of its type or if it's the default.
1114 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001115
1116 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1117 // to preserve previous behaviour.
1118 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001119 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001120 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1121 mService.sendLegacyNetworkBroadcast(nai, state, type);
1122 }
1123
1124 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1125 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001126 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001127 }
1128
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001129 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001130 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001131 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1132 if (list == null || list.isEmpty()) {
1133 return;
1134 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001135 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001136
Hugo Benichi389633f2016-06-21 09:48:07 +09001137 synchronized (mTypeLists) {
1138 if (!list.remove(nai)) {
1139 return;
1140 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001141 }
1142
Lorenzo Colitti49767722015-05-01 00:30:10 +09001143 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001144 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1145 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001146 }
1147
1148 if (!list.isEmpty() && wasFirstNetwork) {
1149 if (DBG) log("Other network available for type " + type +
1150 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001151 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001152 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001153 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001154 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001155 }
1156 }
1157
1158 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001159 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1160 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001161 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001162 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001163 }
1164 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001165
Chalard Jean46bfbf02022-02-02 00:56:25 +09001166 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001167 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001168 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001169 final DetailedState state = nai.networkInfo.getDetailedState();
1170 for (int type = 0; type < mTypeLists.length; type++) {
1171 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001172 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001173 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001174 if (isFirst || contains && isDefault) {
1175 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001176 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001177 }
1178 }
1179 }
1180
Robert Greenwalt94e22142014-07-30 16:31:24 -07001181 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001182 pw.println("mLegacyTypeTracker:");
1183 pw.increaseIndent();
1184 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001185 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001186 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001187 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001188 pw.println();
1189 pw.println("Current state:");
1190 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001191 synchronized (mTypeLists) {
1192 for (int type = 0; type < mTypeLists.length; type++) {
1193 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1194 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001195 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001196 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001197 }
1198 }
1199 pw.decreaseIndent();
1200 pw.decreaseIndent();
1201 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001202 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001203 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001204 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001205
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001206 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001207 /**
1208 * Helper class which parses out priority arguments and dumps sections according to their
1209 * priority. If priority arguments are omitted, function calls the legacy dump command.
1210 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001211 private class LocalPriorityDump {
1212 private static final String PRIORITY_ARG = "--dump-priority";
1213 private static final String PRIORITY_ARG_HIGH = "HIGH";
1214 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1215
1216 LocalPriorityDump() {}
1217
1218 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1219 doDump(fd, pw, new String[] {DIAG_ARG});
1220 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001221 }
1222
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001223 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1224 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001225 }
1226
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001227 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1228 if (args == null) {
1229 dumpNormal(fd, pw, args);
1230 return;
1231 }
1232
1233 String priority = null;
1234 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1235 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1236 argIndex++;
1237 priority = args[argIndex];
1238 }
1239 }
1240
1241 if (PRIORITY_ARG_HIGH.equals(priority)) {
1242 dumpHigh(fd, pw);
1243 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1244 dumpNormal(fd, pw, args);
1245 } else {
1246 // ConnectivityService publishes binder service using publishBinderService() with
1247 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001248 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1249 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001250 // TODO: Integrate into signal dump.
1251 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001252 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001253 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001254 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001255
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001256 /**
1257 * Dependencies of ConnectivityService, for injection in tests.
1258 */
1259 @VisibleForTesting
1260 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001261 public int getCallingUid() {
1262 return Binder.getCallingUid();
1263 }
1264
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001265 /**
1266 * Get system properties to use in ConnectivityService.
1267 */
1268 public MockableSystemProperties getSystemProperties() {
1269 return new MockableSystemProperties();
1270 }
1271
1272 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001273 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1274 */
1275 public ConnectivityResources getResources(@NonNull Context ctx) {
1276 return new ConnectivityResources(ctx);
1277 }
1278
1279 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001280 * Create a HandlerThread to use in ConnectivityService.
1281 */
1282 public HandlerThread makeHandlerThread() {
1283 return new HandlerThread("ConnectivityServiceThread");
1284 }
1285
1286 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001287 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001288 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001289 public NetworkStackClientBase getNetworkStack() {
1290 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001291 }
1292
1293 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001294 * @see ProxyTracker
1295 */
1296 public ProxyTracker makeProxyTracker(@NonNull Context context,
1297 @NonNull Handler connServiceHandler) {
1298 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1299 }
1300
1301 /**
1302 * @see NetIdManager
1303 */
1304 public NetIdManager makeNetIdManager() {
1305 return new NetIdManager();
1306 }
1307
1308 /**
1309 * @see NetworkUtils#queryUserAccess(int, int)
1310 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001311 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1312 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001313 }
1314
1315 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001316 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1317 * requires CAP_NET_ADMIN, which the unit tests do not have.
1318 */
1319 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1320 InetSocketAddress remote) {
1321 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1322 }
1323
1324 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001325 * @see MultinetworkPolicyTracker
1326 */
1327 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1328 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1329 return new MultinetworkPolicyTracker(c, h, r);
1330 }
1331
Aaron Huang330a4c02020-10-27 03:36:19 +08001332 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001333 * @see AutomaticOnOffKeepaliveTracker
1334 */
1335 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1336 @NonNull Context c, @NonNull Handler h) {
1337 return new AutomaticOnOffKeepaliveTracker(c, h);
1338 }
1339
1340 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001341 * @see BatteryStatsManager
1342 */
1343 public void reportNetworkInterfaceForTransports(Context context, String iface,
1344 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001345 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001346 context.getSystemService(BatteryStatsManager.class);
1347 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1348 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001349
1350 public boolean getCellular464XlatEnabled() {
1351 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1352 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001353
1354 /**
1355 * @see PendingIntent#intentFilterEquals
1356 */
1357 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1358 return a.intentFilterEquals(b);
1359 }
1360
1361 /**
1362 * @see LocationPermissionChecker
1363 */
1364 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1365 return new LocationPermissionChecker(context);
1366 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001367
1368 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001369 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001370 *
1371 * This method returns null in versions before T, where carrier privilege
1372 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001373 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001374 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001375 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1376 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1377 if (SdkLevel.isAtLeastT()) {
1378 return new CarrierPrivilegeAuthenticator(context, tm);
1379 } else {
1380 return null;
1381 }
1382 }
1383
1384 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001385 * @see DeviceConfigUtils#isFeatureEnabled
1386 */
1387 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1388 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1389 TETHERING_MODULE_NAME, defaultEnabled);
1390 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001391
1392 /**
1393 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001394 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001395 * @return BpfNetMaps implementation.
1396 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001397 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1398 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001399 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001400
1401 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001402 * @see ClatCoordinator
1403 */
1404 public ClatCoordinator getClatCoordinator(INetd netd) {
1405 return new ClatCoordinator(
1406 new ClatCoordinator.Dependencies() {
1407 @NonNull
1408 public INetd getNetd() {
1409 return netd;
1410 }
1411 });
1412 }
1413
1414 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001415 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1416 */
1417 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1418 final InterfaceParams params = InterfaceParams.getByName(iface);
1419 if (params == null) {
1420 // the interface might have disappeared.
1421 logw("Failed to get interface params for interface " + iface);
1422 return;
1423 }
1424 try {
1425 // converting rateInBytesPerSecond from long to int is safe here because the
1426 // setting's range is limited to INT_MAX.
1427 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001428 Log.i(TAG,
1429 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001430 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1431 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1432 } catch (IOException e) {
1433 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1434 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1435 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1436 + ") failure: ", e);
1437 }
1438 }
1439
1440 /**
1441 * Wraps {@link TcUtils#tcFilterDelDev}
1442 */
1443 public void disableIngressRateLimit(String iface) {
1444 final InterfaceParams params = InterfaceParams.getByName(iface);
1445 if (params == null) {
1446 // the interface might have disappeared.
1447 logw("Failed to get interface params for interface " + iface);
1448 return;
1449 }
1450 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001451 Log.i(TAG,
1452 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001453 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1454 } catch (IOException e) {
1455 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1456 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1457 }
1458 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001459
1460 /**
1461 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1462 */
1463 // TODO: when available in all active branches:
1464 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1465 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1466 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1467 return BroadcastOptionsShimImpl.newInstance(options);
1468 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001469
1470 /**
1471 * Wrapper method for
1472 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1473 *
1474 * @param changeId The ID of the compatibility change in question.
1475 * @param packageName The package name of the app in question.
1476 * @param user The user that the operation is done for.
1477 * @return {@code true} if the change is enabled for the specified package.
1478 */
1479 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1480 @NonNull final UserHandle user) {
1481 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1482 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001483 }
1484
junyulaie7c7d2a2021-01-26 15:29:15 +08001485 public ConnectivityService(Context context) {
1486 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001487 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1488 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001489 }
1490
1491 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001492 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1493 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001494 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001495
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001496 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001497 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001498 mSystemProperties = mDeps.getSystemProperties();
1499 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001500 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001501 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001502 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1503 // Pass limit - 1 to maintain backward compatibility.
1504 // TODO: Remove the workaround.
1505 mNetworkRequestCounter =
1506 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1507 mSystemNetworkRequestCounter =
1508 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001509
Hugo Benichi208c0102016-07-28 17:53:06 +09001510 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001511 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1512 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001513 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001514 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001515 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001516 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1517 mDefaultNetworkRequests.add(mDefaultRequest);
1518 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001519
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001520 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001521 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001522
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001523 // The default WiFi request is a background request so that apps using WiFi are
1524 // migrated to a better network (typically ethernet) when one comes up, instead
1525 // of staying on WiFi forever.
1526 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1527 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1528
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001529 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1530 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1531 NetworkRequest.Type.BACKGROUND_REQUEST);
1532
Chalard Jean0702f982021-09-16 21:50:07 +09001533 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1534 // TODO: Consider making the timer customizable.
1535 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1536 mCellularRadioTimesharingCapable =
1537 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1538
Paul Hu51f816b2022-08-11 14:43:47 +00001539 mNetd = netd;
1540 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001541 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001542 mPermissionMonitor =
1543 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001544 mHandlerThread.start();
1545 mHandler = new InternalHandler(mHandlerThread.getLooper());
1546 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001547 mConnectivityDiagnosticsHandler =
1548 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001549
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001550 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001551 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001552
junyulaie7c7d2a2021-01-26 15:29:15 +08001553 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001554 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001555 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001556 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001557
Wink Saville32506bc2013-06-29 21:10:57 -07001558 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001559 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001560 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001561 mCarrierPrivilegeAuthenticator =
1562 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001563
Sudheer Shanka9967d462021-03-18 19:09:25 +00001564 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001565 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1566 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001567 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001568
1569 final PowerManager powerManager = (PowerManager) context.getSystemService(
1570 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001571 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001572 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001573
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001574 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1575 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001576 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001577 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001578 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001579 mProtectedNetworks.add(p);
1580 } else {
1581 if (DBG) loge("Ignoring protectedNetwork " + p);
1582 }
1583 }
1584
soma, kawata29444ae2019-05-23 09:30:40 +09001585 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1586
James Mattis02220e22021-03-13 19:27:21 -08001587 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001588 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001589 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001590 final IntentFilter userIntentFilter = new IntentFilter();
1591 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1592 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1593 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1594 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001595
James Mattis02220e22021-03-13 19:27:21 -08001596 // Listen to package add/removes for netd
1597 final IntentFilter packageIntentFilter = new IntentFilter();
1598 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1599 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1600 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1601 packageIntentFilter.addDataScheme("package");
1602 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001603 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001604
lucaslind5c2d072021-02-20 18:59:47 +08001605 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001606
Chalard Jean46bfbf02022-02-02 00:56:25 +09001607 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001608 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001609 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001610 } catch (RemoteException | ServiceSpecificException e) {
1611 loge("Error registering event listener :" + e);
1612 }
1613
Erik Kline05f2b402015-04-30 12:58:40 +09001614 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1615 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001616
chiachangwang7c17c282023-02-02 05:58:59 +00001617 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001618 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001619 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001620
1621 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001622 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001623 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1624 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001625 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001626 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1627 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001628
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001629 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001630 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001631 mNetworkRanker =
1632 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1633
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001634 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001635
Chiachang Wangc1215d32020-10-20 15:38:58 +08001636 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001637 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001638
Chalard Jean28018572020-12-21 18:36:52 +09001639 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1640 // request that doesn't allow fallback to the default network. It should never be visible
1641 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1642 // arguments like the handler or the DnsResolver.
1643 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001644 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001645 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001646 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001647 new LinkProperties(), new NetworkCapabilities(),
1648 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001649 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1650 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001651
1652 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001653 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1654 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1655 // Even if it could, running on S would at least require mocking out the BPF map,
1656 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1657 // the bpf syscall. http://aosp/1907693
1658 if (SdkLevel.isAtLeastT()) {
1659 mDscpPolicyTracker = new DscpPolicyTracker();
1660 }
Tyler Wear72388212021-09-09 14:49:02 -07001661 } catch (ErrnoException e) {
1662 loge("Unable to create DscpPolicyTracker");
1663 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001664
1665 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1666 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001667
1668 if (SdkLevel.isAtLeastT()) {
1669 mCdmps = new CompanionDeviceManagerProxyService(context);
1670 } else {
1671 mCdmps = null;
1672 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001673 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001674
Xiao Ma0a171c02022-01-23 16:14:51 +00001675 /**
1676 * Check whether or not the device supports Ethernet transport.
1677 */
1678 public static boolean deviceSupportsEthernet(final Context context) {
1679 final PackageManager pm = context.getPackageManager();
1680 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1681 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1682 }
1683
Chalard Jean46adcf32018-04-18 20:18:38 +09001684 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001685 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1686 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001687 }
1688
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001689 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1690 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001691 final NetworkCapabilities netCap = new NetworkCapabilities();
1692 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001693 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001694 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001695 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001696 return netCap;
1697 }
1698
James Mattis45d81842021-01-10 14:24:24 -08001699 private NetworkRequest createDefaultRequest() {
1700 return createDefaultInternetRequestForTransport(
1701 TYPE_NONE, NetworkRequest.Type.REQUEST);
1702 }
1703
lucaslin3ba7cc22022-12-19 02:35:33 +00001704 private NetworkRequest createVpnRequest() {
1705 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1706 .withoutDefaultCapabilities()
1707 .addTransportType(TRANSPORT_VPN)
1708 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1709 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1710 .build();
1711 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1712 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1713 }
1714
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001715 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001716 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001717 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001718 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001719 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001720 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001721 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001722 netCap.addTransportType(transportType);
1723 }
James Mattis45d81842021-01-10 14:24:24 -08001724 return createNetworkRequest(type, netCap);
1725 }
1726
1727 private NetworkRequest createNetworkRequest(
1728 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001729 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001730 }
1731
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001732 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1733 NetworkRequest.Type type) {
1734 final NetworkCapabilities netCap = new NetworkCapabilities();
1735 netCap.clearAll();
1736 netCap.addCapability(capability);
1737 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1738 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1739 }
1740
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001741 // Used only for testing.
1742 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001743 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001744 // changing ContentResolver to make registerContentObserver non-final).
1745 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1746 // by subclassing SettingsObserver.
1747 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001748 void updateAlwaysOnNetworks() {
1749 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001750 }
1751
Erik Kline9a62f012018-03-21 07:18:33 -07001752 // See FakeSettingsProvider comment above.
1753 @VisibleForTesting
1754 void updatePrivateDnsSettings() {
1755 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1756 }
1757
paulhu51f77dc2021-06-07 02:34:20 +00001758 @VisibleForTesting
1759 void updateMobileDataPreferredUids() {
1760 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1761 }
1762
Patrick Rohr2857ac42022-01-21 14:58:16 +01001763 @VisibleForTesting
1764 void updateIngressRateLimit() {
1765 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1766 }
1767
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001768 private void handleAlwaysOnNetworkRequest(
1769 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001770 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001771 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001772 handleAlwaysOnNetworkRequest(networkRequest, enable);
1773 }
1774
1775 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001776 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001777 if (enable == isEnabled) {
1778 return; // Nothing to do.
1779 }
1780
1781 if (enable) {
1782 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001783 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001784 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001785 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001786 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001787 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1788 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001789 }
1790 }
1791
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001792 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001793 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1794 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1795 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1796 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001797 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1798 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001799 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001800 }
1801
paulhu51f77dc2021-06-07 02:34:20 +00001802 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001803 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001804 private void registerSettingsCallbacks() {
1805 // Watch for global HTTP proxy changes.
1806 mSettingsObserver.observe(
1807 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1808 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1809
Chalard Jean46bfbf02022-02-02 00:56:25 +09001810 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001811 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001812 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001813 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1814
Chalard Jean46bfbf02022-02-02 00:56:25 +09001815 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001816 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001817 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001818 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001819
1820 // Watch for mobile data preferred uids changes.
1821 mSettingsObserver.observe(
1822 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1823 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001824
1825 // Watch for ingress rate limit changes.
1826 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001827 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001828 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1829 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001830 }
1831
Erik Kline31b4a9e2018-01-11 21:07:29 +09001832 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001833 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1834 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001835 }
1836 }
1837
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001838 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001839 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1840 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001841 return mNextNetworkRequestId++;
1842 }
1843
junyulai74f9a8b2018-06-13 15:00:37 +08001844 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001845 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001846 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001847 if (network == null) {
1848 return null;
1849 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001850 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001851 }
1852
1853 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001854 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001855 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001856 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001857 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001858
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001859 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001860 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001861 private NetworkAgentInfo getVpnForUid(int uid) {
1862 synchronized (mNetworkForNetId) {
1863 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1864 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001865 if (nai.isVPN() && nai.everConnected()
1866 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001867 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001868 }
1869 }
1870 }
1871 return null;
1872 }
1873
Chalard Jean46bfbf02022-02-02 00:56:25 +09001874 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001875 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001876 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001877 final NetworkAgentInfo nai = getVpnForUid(uid);
1878 if (nai != null) return nai.declaredUnderlyingNetworks;
1879 return null;
1880 }
1881
Lorenzo Colittia7574052021-01-19 01:33:05 +09001882 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001883 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001884
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001885 final Network[] networks = getVpnUnderlyingNetworks(uid);
1886 if (networks != null) {
1887 // getUnderlyingNetworks() returns:
1888 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1889 // empty array => the VPN explicitly said "no default network".
1890 // non-empty array => the VPN specified one or more default networks; we use the
1891 // first one.
1892 if (networks.length > 0) {
1893 nai = getNetworkAgentInfoForNetwork(networks[0]);
1894 } else {
1895 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001896 }
1897 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001898 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001899 }
1900
1901 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001902 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001903 */
paulhu7aeba372020-12-30 00:42:19 +08001904 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1905 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001906 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001907 if (ignoreBlocked) {
1908 return false;
1909 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001910 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001911 final long ident = Binder.clearCallingIdentity();
1912 try {
1913 final boolean metered = nc == null ? true : nc.isMetered();
1914 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1915 } finally {
1916 Binder.restoreCallingIdentity(ident);
1917 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001918 }
1919
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001920 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001921 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1922 return;
1923 }
Hugo Benichi47011212017-03-30 10:46:05 +09001924 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001925 synchronized (mBlockedAppUids) {
1926 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001927 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001928 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001929 blocked = false;
1930 } else {
1931 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001932 }
1933 }
Hugo Benichi47011212017-03-30 10:46:05 +09001934 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1935 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1936 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001937 }
1938
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001939 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001940 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1941 return;
1942 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001943 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001944 final int requestId = nri.getActiveRequest() != null
1945 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001946 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001947 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001948 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001949 }
1950
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001951 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001952 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001953 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001954 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001955 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001956 @NonNull
1957 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1958 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001959 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1960 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1961 // but only exists if an app asks about them or requests them. Ensure the requesting app
1962 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001963 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001964 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1965 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1966 null /* extraInfo */);
1967 }
1968 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001969 return filtered;
1970 }
1971
1972 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1973 boolean ignoreBlocked) {
1974 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1975 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001976 }
1977
1978 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001979 * Return NetworkInfo for the active (i.e., connected) network interface.
1980 * It is assumed that at most one network is active at a time. If more
1981 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001982 * @return the info for the active network, or {@code null} if none is
1983 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001984 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001985 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001986 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001987 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001988 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001989 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001990 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1991 if (nai == null) return null;
1992 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1993 maybeLogBlockedNetworkInfo(networkInfo, uid);
1994 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001995 }
1996
Paul Jensen1f567382015-02-13 14:18:39 -05001997 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001998 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001999 public Network getActiveNetwork() {
2000 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002001 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002002 }
2003
2004 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002005 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002006 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002007 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002008 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002009 }
2010
Chalard Jean46bfbf02022-02-02 00:56:25 +09002011 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002012 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002013 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2014 if (vpnNai != null) {
2015 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2016 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2017 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002018 }
Paul Jensen1f567382015-02-13 14:18:39 -05002019 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002020
James Mattis2516da32021-01-31 17:06:19 -08002021 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002022 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2023 ignoreBlocked)) {
2024 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002025 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002026 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002027 }
2028
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002029 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002030 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002031 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002032 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002033 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2034 if (nai == null) return null;
2035 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002036 }
2037
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002038 /** Returns a NetworkInfo object for a network that doesn't exist. */
2039 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2040 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2041 getNetworkTypeName(networkType), "" /* subtypeName */);
2042 info.setIsAvailable(true);
2043 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2044 // background data is restricted.
2045 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2046 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2047 ? DetailedState.BLOCKED
2048 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002049 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2050 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002051 return info;
2052 }
2053
Lorenzo Colittia7574052021-01-19 01:33:05 +09002054 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002055 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2056 return null;
2057 }
2058 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002059 if (nai == null) {
2060 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002061 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002062 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2063 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002064 }
2065
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002066 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002067 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002068 public NetworkInfo getNetworkInfo(int networkType) {
2069 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002070 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002071 if (getVpnUnderlyingNetworks(uid) != null) {
2072 // A VPN is active, so we may need to return one of its underlying networks. This
2073 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002074 // getNetworkAgentInfoForUid.
2075 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2076 if (nai == null) return null;
2077 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2078 if (networkInfo.getType() == networkType) {
2079 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002080 }
2081 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002082 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002083 }
2084
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002085 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002086 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002087 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002088 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002089 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002090 if (nai == null) return null;
2091 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002092 }
2093
2094 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002095 public NetworkInfo[] getAllNetworkInfo() {
2096 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002097 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002098 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2099 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002100 NetworkInfo info = getNetworkInfo(networkType);
2101 if (info != null) {
2102 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002103 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002104 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002105 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002106 }
2107
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002108 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002109 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002110 public Network getNetworkForType(int networkType) {
2111 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002112 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2113 return null;
2114 }
2115 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2116 if (nai == null) {
2117 return null;
2118 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002119 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002120 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2121 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002122 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002123 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002124 }
2125
2126 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002127 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002128 public Network[] getAllNetworks() {
2129 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002130 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002131 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002132 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002133 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002134 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002135 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002136 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002137 }
2138
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002139 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002140 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002141 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002142 // The basic principle is: if an app's traffic could possibly go over a
2143 // network, without the app doing anything multinetwork-specific,
2144 // (hence, by "default"), then include that network's capabilities in
2145 // the array.
2146 //
2147 // In the normal case, app traffic only goes over the system's default
2148 // network connection, so that's the only network returned.
2149 //
2150 // With a VPN in force, some app traffic may go into the VPN, and thus
2151 // over whatever underlying networks the VPN specifies, while other app
2152 // traffic may go over the system default network (e.g.: a split-tunnel
2153 // VPN, or an app disallowed by the VPN), so the set of networks
2154 // returned includes the VPN's underlying networks and the system
2155 // default.
2156 enforceAccessPermission();
2157
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002158 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002159
James Mattis2516da32021-01-31 17:06:19 -08002160 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2161 if (!nri.isBeingSatisfied()) {
2162 continue;
2163 }
2164 final NetworkAgentInfo nai = nri.getSatisfier();
2165 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2166 if (null != nc
2167 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2168 && !result.containsKey(nai.network)) {
2169 result.put(
2170 nai.network,
2171 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002172 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002173 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2174 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002175 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002176 }
2177
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002178 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002179 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002180 if (null != networks) {
2181 for (final Network network : networks) {
2182 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2183 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002184 result.put(
2185 network,
2186 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002187 nc,
2188 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002189 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002190 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002191 }
2192 }
2193 }
2194
2195 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2196 out = result.values().toArray(out);
2197 return out;
2198 }
2199
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002200 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002201 public boolean isNetworkSupported(int networkType) {
2202 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002203 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002204 }
2205
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002206 /**
2207 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002208 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002209 * @return the ip properties for the active network, or {@code null} if
2210 * none is active
2211 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002212 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002213 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002214 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002215 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002216 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2217 if (nai == null) return null;
2218 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002219 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002220 }
2221
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002222 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002223 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002224 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002225 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002226 final LinkProperties lp = getLinkProperties(nai);
2227 if (lp == null) return null;
2228 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002229 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002230 }
2231
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002232 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002233 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002234 public LinkProperties getLinkProperties(Network network) {
2235 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002236 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2237 if (lp == null) return null;
2238 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002239 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002240 }
2241
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002242 @Nullable
2243 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002244 if (nai == null) {
2245 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002246 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002247 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002248 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002249 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002250 }
2251
lucaslinc582d502022-01-27 09:07:00 +08002252 @Override
2253 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002254 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002255 @NonNull String packageName, @Nullable String callingAttributionTag) {
2256 Objects.requireNonNull(packageName);
2257 Objects.requireNonNull(lp);
2258 enforceNetworkStackOrSettingsPermission();
2259 if (!checkAccessPermission(-1 /* pid */, uid)) {
2260 return null;
2261 }
2262 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2263 }
2264
Qingxi Lib2748102020-01-08 12:51:49 -08002265 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2266 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2267 }
2268
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002269 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002270 if (nai == null) return null;
2271 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002272 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002273 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002274 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002275 }
2276
2277 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002278 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2279 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002280 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002281 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002282 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002283 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002284 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002285 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002286 }
2287
lucaslinc582d502022-01-27 09:07:00 +08002288 @Override
lucaslind2b06132022-03-02 10:56:57 +08002289 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2290 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2291 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002292 Objects.requireNonNull(nc);
2293 Objects.requireNonNull(packageName);
2294 enforceNetworkStackOrSettingsPermission();
2295 if (!checkAccessPermission(-1 /* pid */, uid)) {
2296 return null;
2297 }
2298 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2299 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2300 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2301 callingAttributionTag);
2302 }
2303
lucaslin69e1aa92022-03-22 18:15:09 +08002304 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2305 if (nc.getUnderlyingNetworks() != null
2306 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2307 nc.setUnderlyingNetworks(null);
2308 }
2309 }
2310
Qingxi Libb8da982020-01-17 17:54:27 -08002311 @VisibleForTesting
2312 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002313 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002314 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2315 // this would be expensive (one more permission check every time any NC callback is
2316 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2317 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2318 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002319 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002320 if (!checkSettingsPermission(callerPid, callerUid)) {
2321 newNc.setUids(null);
2322 newNc.setSSID(null);
2323 }
Etan Cohen107ae952018-12-30 17:59:59 -08002324 if (newNc.getNetworkSpecifier() != null) {
2325 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2326 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002327 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2328 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2329 newNc.setAdministratorUids(new int[0]);
2330 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002331 if (!checkAnyPermissionOf(
2332 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002333 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002334 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002335 }
lucaslin69e1aa92022-03-22 18:15:09 +08002336 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002337
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002338 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002339 }
2340
Roshan Pius98f59ec2021-02-23 08:47:39 -08002341 /**
2342 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002343 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002344 * NetworkCapabilities.
2345 * Note: This wrapper does not support any sort of invalidation and thus must not be
2346 * persistent or long-lived. It may only be used for the time necessary to
2347 * compute the redactions required by one particular NetworkCallback or
2348 * synchronous call.
2349 */
2350 private class RedactionPermissionChecker {
2351 private final int mCallingPid;
2352 private final int mCallingUid;
2353 @NonNull private final String mCallingPackageName;
2354 @Nullable private final String mCallingAttributionTag;
2355
2356 private Boolean mHasLocationPermission = null;
2357 private Boolean mHasLocalMacAddressPermission = null;
2358 private Boolean mHasSettingsPermission = null;
2359
2360 RedactionPermissionChecker(int callingPid, int callingUid,
2361 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2362 mCallingPid = callingPid;
2363 mCallingUid = callingUid;
2364 mCallingPackageName = callingPackageName;
2365 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002366 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002367
2368 private boolean hasLocationPermissionInternal() {
2369 final long token = Binder.clearCallingIdentity();
2370 try {
2371 return mLocationPermissionChecker.checkLocationPermission(
2372 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2373 null /* message */);
2374 } finally {
2375 Binder.restoreCallingIdentity(token);
2376 }
2377 }
2378
2379 /**
2380 * Returns whether the app holds location permission or not (might return cached result
2381 * if the permission was already checked before).
2382 */
2383 public boolean hasLocationPermission() {
2384 if (mHasLocationPermission == null) {
2385 // If there is no cached result, perform the check now.
2386 mHasLocationPermission = hasLocationPermissionInternal();
2387 }
2388 return mHasLocationPermission;
2389 }
2390
2391 /**
2392 * Returns whether the app holds local mac address permission or not (might return cached
2393 * result if the permission was already checked before).
2394 */
2395 public boolean hasLocalMacAddressPermission() {
2396 if (mHasLocalMacAddressPermission == null) {
2397 // If there is no cached result, perform the check now.
2398 mHasLocalMacAddressPermission =
2399 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2400 }
2401 return mHasLocalMacAddressPermission;
2402 }
2403
2404 /**
2405 * Returns whether the app holds settings permission or not (might return cached
2406 * result if the permission was already checked before).
2407 */
2408 public boolean hasSettingsPermission() {
2409 if (mHasSettingsPermission == null) {
2410 // If there is no cached result, perform the check now.
2411 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2412 }
2413 return mHasSettingsPermission;
2414 }
2415 }
2416
2417 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2418 @NetworkCapabilities.NetCapability long redaction) {
2419 return (redactions & redaction) != 0;
2420 }
2421
2422 /**
2423 * Use the provided |applicableRedactions| to check the receiving app's
2424 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2425 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2426 * before being sent to the corresponding app.
2427 */
2428 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2429 @NetworkCapabilities.RedactionType long applicableRedactions,
2430 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2431 boolean includeLocationSensitiveInfo) {
2432 long redactions = applicableRedactions;
2433 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2434 if (includeLocationSensitiveInfo
2435 && redactionPermissionChecker.hasLocationPermission()) {
2436 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2437 }
2438 }
2439 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2440 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2441 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2442 }
2443 }
2444 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2445 if (redactionPermissionChecker.hasSettingsPermission()) {
2446 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2447 }
2448 }
2449 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002450 }
2451
Qingxi Lib2748102020-01-08 12:51:49 -08002452 @VisibleForTesting
2453 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002454 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002455 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002456 int callingPid, int callingUid, @NonNull String callingPkgName,
2457 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002458 if (nc == null) {
2459 return null;
2460 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002461 // Avoid doing location permission check if the transport info has no location sensitive
2462 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002463 final RedactionPermissionChecker redactionPermissionChecker =
2464 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2465 callingAttributionTag);
2466 final long redactions = retrieveRequiredRedactions(
2467 nc.getApplicableRedactions(), redactionPermissionChecker,
2468 includeLocationSensitiveInfo);
2469 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002470 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002471 // TODO : calling UID is redacted because apps should generally not know what UID is
2472 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002473 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002474 newNc.setOwnerUid(INVALID_UID);
2475 return newNc;
2476 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002477 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2478 if (nc.hasTransport(TRANSPORT_VPN)) {
2479 // Owner UIDs already checked above. No need to re-check.
2480 return newNc;
2481 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002482 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2483 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002484 // compatibility for older apps.
2485 if (!includeLocationSensitiveInfo
2486 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002487 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002488 newNc.setOwnerUid(INVALID_UID);
2489 return newNc;
2490 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002491 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002492 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002493 newNc.setOwnerUid(INVALID_UID);
2494 }
Qingxi Lib2748102020-01-08 12:51:49 -08002495 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002496 }
2497
lucaslinc582d502022-01-27 09:07:00 +08002498 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002499 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2500 LinkProperties lp, int callerPid, int callerUid) {
2501 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002502 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2503 // this would be expensive (one more permission check every time any LP callback is
2504 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2505 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2506 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002507
2508 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2509 final boolean needsSanitization =
2510 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2511 if (!needsSanitization) {
2512 return new LinkProperties(lp);
2513 }
2514
2515 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002516 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002517 }
2518
2519 final LinkProperties newLp = new LinkProperties(lp);
2520 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2521 // object gets parceled.
2522 newLp.setCaptivePortalApiUrl(null);
2523 newLp.setCaptivePortalData(null);
2524 return newLp;
2525 }
2526
Roshan Pius08c94fb2020-01-16 12:17:17 -08002527 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2528 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002529 // There is no need to track the effective UID of the request here. If the caller
2530 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002531 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002532 // Unprivileged apps can only pass in null or their own UID.
2533 if (nc.getUids() == null) {
2534 // If the caller passes in null, the callback will also match networks that do not
2535 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2536 // In this case, redact everything in the request immediately. This ensures that the
2537 // app is not able to get any redacted information by filing an unredacted request
2538 // and observing whether the request matches something.
2539 if (nc.getNetworkSpecifier() != null) {
2540 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2541 }
2542 } else {
2543 nc.setSingleUid(callerUid);
2544 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002545 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002546 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002547 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002548
2549 // Clear owner UID; this can never come from an app.
2550 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002551 }
2552
Chalard Jean38354d12018-03-20 19:13:57 +09002553 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002554 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002555 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2556 }
2557 }
2558
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002559 @Override
2560 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2561 enforceAccessPermission();
2562 final int callerUid = Binder.getCallingUid();
2563 final long token = Binder.clearCallingIdentity();
2564 try {
2565 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2566 } finally {
2567 Binder.restoreCallingIdentity(token);
2568 }
2569 }
2570
junyulaiebd15162021-03-03 12:09:05 +08002571 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002572 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002573 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002574 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002575 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002576
Serik Beketayev05130302021-01-15 16:47:25 -08002577 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002578 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002579 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2580 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002581 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002582 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002583 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002584 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2585 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002586 }
2587 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002588 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002589 }
2590
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002591 @Override
junyulaiebd15162021-03-03 12:09:05 +08002592 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002593 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002594 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002595 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002596
2597 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2598 for (Network network : getAllNetworks()) {
2599 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002600 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002601 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2602 // NetworkCapabilities, which may contain UIDs of apps to which the
2603 // network applies. Should the UIDs be cleared so as not to leak or
2604 // interfere ?
2605 result.add(nai.getNetworkStateSnapshot());
2606 }
2607 }
2608 return result;
2609 }
2610
2611 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002612 public boolean isActiveNetworkMetered() {
2613 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002614
Qingxi Lib2748102020-01-08 12:51:49 -08002615 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002616 if (caps != null) {
2617 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2618 } else {
2619 // Always return the most conservative value
2620 return true;
2621 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002622 }
2623
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002624 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002625 * Ensures that the system cannot call a particular method.
2626 */
2627 private boolean disallowedBecauseSystemCaller() {
2628 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002629 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2630 // for devices launched with Q and above. However, existing devices upgrading to Q and
2631 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002632 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002633 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002634 log("This method exists only for app backwards compatibility"
2635 + " and must not be called by system services.");
2636 return true;
2637 }
2638 return false;
2639 }
2640
paulhub2c28682021-08-18 18:35:54 +08002641 private int getAppUid(final String app, final UserHandle user) {
2642 final PackageManager pm =
2643 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2644 final long token = Binder.clearCallingIdentity();
2645 try {
2646 return pm.getPackageUid(app, 0 /* flags */);
2647 } catch (PackageManager.NameNotFoundException e) {
2648 return -1;
2649 } finally {
2650 Binder.restoreCallingIdentity(token);
2651 }
2652 }
2653
2654 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2655 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2656 if (getAppUid(packageName, user) != callingUid) {
2657 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2658 }
2659 }
2660
Lorenzo Colitti23862912018-09-28 11:31:55 +09002661 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002662 * Ensure that a network route exists to deliver traffic to the specified
2663 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002664 * @param networkType the type of the network over which traffic to the
2665 * specified host is to be routed
2666 * @param hostAddress the IP address of the host to which the route is
2667 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002668 * @return {@code true} on success, {@code false} on failure
2669 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002670 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002671 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2672 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002673 if (disallowedBecauseSystemCaller()) {
2674 return false;
2675 }
paulhub2c28682021-08-18 18:35:54 +08002676 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002677 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002678 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002679 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002680 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002681
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002682 InetAddress addr;
2683 try {
2684 addr = InetAddress.getByAddress(hostAddress);
2685 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002686 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002687 return false;
2688 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002689
The Android Open Source Project28527d22009-03-03 19:31:44 -08002690 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002691 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002692 return false;
2693 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002694
2695 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2696 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002697 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002698 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2699 } else {
2700 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2701 }
2702 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002703 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002704
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002705 DetailedState netState;
2706 synchronized (nai) {
2707 netState = nai.networkInfo.getDetailedState();
2708 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002709
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002710 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002711 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002712 log("requestRouteToHostAddress on down network "
2713 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002714 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002715 }
2716 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002717 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002718
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002719 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002720 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002721 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002722 LinkProperties lp;
2723 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002724 synchronized (nai) {
2725 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002726 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002727 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002728 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002729 if (DBG) {
2730 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2731 }
Wink Saville32506bc2013-06-29 21:10:57 -07002732 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002733 } finally {
2734 Binder.restoreCallingIdentity(token);
2735 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002736 }
2737
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002738 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002739 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002740 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002741 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002742 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002743 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002744 if (bestRoute.getGateway().equals(addr)) {
2745 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002746 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002747 } else {
2748 // if we will connect to this through another route, add a direct route
2749 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002750 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002751 }
2752 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002753 if (DBG) log("Adding legacy route " + bestRoute +
2754 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002755
2756 final String dst = bestRoute.getDestinationLinkAddress().toString();
2757 final String nextHop = bestRoute.hasGateway()
2758 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002759 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002760 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2761 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002762 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002763 return false;
2764 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002765 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002766 }
2767
paulhu7c0a2e62021-01-08 00:51:49 +08002768 class DnsResolverUnsolicitedEventCallback extends
2769 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002770 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002771 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002772 try {
2773 mHandler.sendMessage(mHandler.obtainMessage(
2774 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002775 new PrivateDnsValidationUpdate(event.netId,
2776 InetAddresses.parseNumericAddress(event.ipAddress),
2777 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002778 } catch (IllegalArgumentException e) {
2779 loge("Error parsing ip address in validation event");
2780 }
2781 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002782
2783 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002784 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2785 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002786 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2787 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2788 // event callback for certain nai. e.g. cellular. Register here to pass to
2789 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002790 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002791 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2792 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002793 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002794 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002795 }
2796 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002797
2798 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002799 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2800 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2801 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002802 }
dalyk1720e542018-03-05 12:42:22 -05002803
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002804 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002805 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002806 return this.VERSION;
2807 }
2808
2809 @Override
2810 public String getInterfaceHash() {
2811 return this.HASH;
2812 }
paulhu7c0a2e62021-01-08 00:51:49 +08002813 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002814
2815 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002816 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2817 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002818
paulhu7c0a2e62021-01-08 00:51:49 +08002819 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002820 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002821 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002822 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002823 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002824 }
2825 }
2826
Sudheer Shanka9967d462021-03-18 19:09:25 +00002827 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002828 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002829 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002830 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2831 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002832 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002833 };
2834
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002835 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002836 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002837 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002838 }
2839
paulhu1a407652019-03-22 16:35:06 +08002840 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2841 for (String permission : permissions) {
2842 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2843 return true;
2844 }
2845 }
2846 return false;
2847 }
2848
Paul Jensen83f5d572014-08-29 09:54:01 -04002849 private void enforceInternetPermission() {
2850 mContext.enforceCallingOrSelfPermission(
2851 android.Manifest.permission.INTERNET,
2852 "ConnectivityService");
2853 }
2854
The Android Open Source Project28527d22009-03-03 19:31:44 -08002855 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002856 mContext.enforceCallingOrSelfPermission(
2857 android.Manifest.permission.ACCESS_NETWORK_STATE,
2858 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002859 }
2860
lucaslinc582d502022-01-27 09:07:00 +08002861 private boolean checkAccessPermission(int pid, int uid) {
2862 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2863 == PERMISSION_GRANTED;
2864 }
2865
paulhua6ee2122021-02-22 15:40:43 +08002866 /**
2867 * Performs a strict and comprehensive check of whether a calling package is allowed to
2868 * change the state of network, as the condition differs for pre-M, M+, and
2869 * privileged/preinstalled apps. The caller is expected to have either the
2870 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2871 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2872 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2873 * permission and cannot be revoked. See http://b/23597341
2874 *
2875 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2876 * of this app will be updated to the current time.
2877 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002878 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002879 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2880 == PackageManager.PERMISSION_GRANTED) {
2881 return;
2882 }
2883
2884 if (callingPkg == null) {
2885 throw new SecurityException("Calling package name is null.");
2886 }
2887
2888 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2889 final int uid = mDeps.getCallingUid();
2890 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2891 callingPkg, callingAttributionTag, null /* message */);
2892
2893 if (mode == AppOpsManager.MODE_ALLOWED) {
2894 return;
2895 }
2896
2897 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2898 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2899 return;
2900 }
2901
2902 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2903 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2904 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002905 }
2906
Charles He9369e612017-05-15 17:07:18 +01002907 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002908 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002909 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002910 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002911 }
2912
Quang Luong98858d62023-02-11 00:25:24 +00002913 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08002914 enforceAnyPermissionOf(mContext,
2915 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00002916 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08002917 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2918 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
2919 }
2920
paulhu8e96a752019-08-12 16:25:11 +08002921 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002922 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002923 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002924 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002925 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002926 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002927 }
2928
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002929 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002930 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002931 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002932 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002933 android.Manifest.permission.NETWORK_SETTINGS,
2934 android.Manifest.permission.NETWORK_FACTORY,
2935 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2936 }
2937
2938 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002939 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002940 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002941 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002942 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2943 android.Manifest.permission.NETWORK_FACTORY,
2944 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2945 }
2946
lucaslin69e1aa92022-03-22 18:15:09 +08002947 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2948 return PERMISSION_GRANTED == mContext.checkPermission(
2949 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2950 || PERMISSION_GRANTED == mContext.checkPermission(
2951 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2952 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002953 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002954 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002955 }
2956
Chalard Jean9a396cc2018-02-21 18:43:54 +09002957 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002958 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002959 android.Manifest.permission.NETWORK_SETTINGS,
2960 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002961 }
2962
2963 private boolean checkSettingsPermission(int pid, int uid) {
2964 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002965 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2966 || PERMISSION_GRANTED == mContext.checkPermission(
2967 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002968 }
2969
paulhu8e96a752019-08-12 16:25:11 +08002970 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002971 enforceNetworkStackPermissionOr(mContext,
2972 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002973 }
2974
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002975 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002976 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002977 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002978 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002979 }
2980
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002981 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002982 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002983 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2984 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002985 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002986 }
2987
James Mattis8378aec2021-01-26 14:05:36 -08002988 private void enforceOemNetworkPreferencesPermission() {
2989 mContext.enforceCallingOrSelfPermission(
2990 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2991 "ConnectivityService");
2992 }
2993
James Mattisfa270db2021-05-31 17:11:10 -07002994 private void enforceManageTestNetworksPermission() {
2995 mContext.enforceCallingOrSelfPermission(
2996 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2997 "ConnectivityService");
2998 }
2999
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003000 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003001 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003002 android.Manifest.permission.NETWORK_STACK,
3003 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003004 }
3005
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003006 private boolean checkNetworkStackPermission(int pid, int uid) {
3007 return checkAnyPermissionOf(pid, uid,
3008 android.Manifest.permission.NETWORK_STACK,
3009 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3010 }
3011
paulhu1a407652019-03-22 16:35:06 +08003012 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
3013 return checkAnyPermissionOf(pid, uid,
3014 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003015 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3016 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003017 }
3018
Paul Hu8fc2a552022-05-04 18:44:42 +08003019 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3020 boolean checkUidsAllowedList) {
3021 if (PermissionUtils.checkAnyPermissionOf(mContext,
3022 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3023 return true;
3024 }
3025
3026 // fallback to ConnectivityInternalPermission
3027 // TODO: Remove this fallback check after all apps have declared
3028 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3029 if (PermissionUtils.checkAnyPermissionOf(mContext,
3030 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3031 return true;
3032 }
3033
3034 // Check whether uid is in allowed on restricted networks list.
3035 if (checkUidsAllowedList
3036 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3037 return true;
3038 }
3039 return false;
3040 }
3041
3042 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3043 final int callingUid = mDeps.getCallingUid();
3044 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3045 throw new SecurityException("ConnectivityService: user " + callingUid
3046 + " has no permission to access restricted network.");
3047 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003048 }
3049
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003050 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003051 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003052 }
3053
Roshan Pius98f59ec2021-02-23 08:47:39 -08003054 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3055 return PERMISSION_GRANTED == mContext.checkPermission(
3056 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3057 }
3058
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003059 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003060 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003061 }
3062
3063 private void sendInetConditionBroadcast(NetworkInfo info) {
3064 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3065 }
3066
Wink Saville4f0de1e2011-08-04 15:01:58 -07003067 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003068 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003069 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003070 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003071 if (info.isFailover()) {
3072 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3073 info.setFailover(false);
3074 }
3075 if (info.getReason() != null) {
3076 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3077 }
3078 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003079 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3080 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003081 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003082 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003083 return intent;
3084 }
3085
3086 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3087 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3088 }
3089
Michael Groover73f69482023-01-27 11:01:25 -06003090 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3091 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003092 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3093 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003094 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003095 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003096 if (!mSystemReady
3097 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003098 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003099 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003100 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003101 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003102 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003103 }
3104
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003105 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003106 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003107 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003108 final NetworkInfo ni = intent.getParcelableExtra(
3109 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003110 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3111 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003112 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003113 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003114 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003115 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003116 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003117 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003118 } finally {
3119 Binder.restoreCallingIdentity(ident);
3120 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003121 }
3122 }
3123
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003124 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3125 NetworkInfo info) {
3126 // Delivery group policy APIs are only available on U+.
3127 if (!SdkLevel.isAtLeastU()) return;
3128
3129 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3130 try {
3131 // This allows us to discard older broadcasts still waiting to be delivered
3132 // which have the same namespace and key.
3133 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3134 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3135 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003136 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003137 } catch (UnsupportedApiLevelException e) {
3138 Log.wtf(TAG, "Using unsupported API" + e);
3139 }
3140 }
3141
3142 @VisibleForTesting
3143 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3144 final StringBuilder sb = new StringBuilder();
3145 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3146 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3147 sb.append(info.getExtraInfo());
3148 return sb.toString();
3149 }
3150
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003151 /**
Aaron Huang96011892020-06-27 07:18:23 +08003152 * Called by SystemServer through ConnectivityManager when the system is ready.
3153 */
3154 @Override
3155 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003156 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003157 throw new SecurityException("Calling Uid is not system uid.");
3158 }
3159 systemReadyInternal();
3160 }
3161
3162 /**
3163 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003164 */
3165 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003166 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003167 // Load flags after PackageManager is ready to query module version
3168 mFlags.loadFlags(mDeps, mContext);
3169
Aaron Huang9a57acf2020-12-08 10:03:29 +08003170 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3171 // listening network request which is sent by MultipathPolicyTracker won't be added
3172 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3173 // be called after PermissionMonitor#startMonitoring().
3174 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3175 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3176 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003177 final ConditionVariable startMonitoringDone = new ConditionVariable();
3178 mHandler.post(() -> {
3179 mPermissionMonitor.startMonitoring();
3180 startMonitoringDone.open();
3181 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003182 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003183 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003184
Hugo Benichie5220992017-04-26 14:53:28 +09003185 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003186 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003187 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003188 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003189 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003190 }
3191 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003192
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003193 // Create network requests for always-on networks.
3194 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003195
3196 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003197 // Note that updating can be skipped here if the list is empty only because no uid
3198 // rules are applied before system ready. Normally, the empty uid list means to clear
3199 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003200 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3201 updateMobileDataPreferredUids();
3202 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003203
3204 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3205 if (SdkLevel.isAtLeastT()) {
3206 mBpfNetMaps.setPullAtomCallback(mContext);
3207 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003208 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3209 // have permission problem. While CV#block() is unbounded in time and can in principle block
3210 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3211 // could have blocked forever too.
3212 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003213 }
3214
The Android Open Source Project28527d22009-03-03 19:31:44 -08003215 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003216 * Start listening for default data network activity state changes.
3217 */
3218 @Override
3219 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003220 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003221 }
3222
3223 /**
3224 * Stop listening for default data network activity state changes.
3225 */
3226 @Override
3227 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003228 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003229 }
3230
3231 /**
3232 * Check whether the default network radio is currently active.
3233 */
3234 @Override
3235 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003236 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003237 }
3238
3239 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003240 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003241 * and set it on it's iface.
3242 */
Junyu Lai970963e2022-10-25 15:46:47 +08003243 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003244 final String iface = newLp.getInterfaceName();
3245 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003246 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003247 // Silently ignore unset MTU value.
3248 return;
3249 }
Hansen Kurli04252032022-12-07 11:21:49 +00003250 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3251 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3252 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003253 return;
3254 }
Hansen Kurli04252032022-12-07 11:21:49 +00003255 // Cannot set MTU without interface name
3256 if (TextUtils.isEmpty(iface)) {
3257 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003258 return;
3259 }
sy.yun4aa73922013-09-02 05:24:09 +09003260
Hansen Kurli04252032022-12-07 11:21:49 +00003261 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3262 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003263 return;
3264 }
3265
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003266 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003267 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003268 mNetd.interfaceSetMtu(iface, mtu);
3269 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003270 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003271 }
3272 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003273
Chenbo Feng15416292018-11-08 17:36:21 -08003274 @VisibleForTesting
3275 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003276
Junyu Lai970963e2022-10-25 15:46:47 +08003277 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003278 String[] values = null;
3279 if (tcpBufferSizes != null) {
3280 values = tcpBufferSizes.split(",");
3281 }
3282
3283 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003284 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003285 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3286 values = tcpBufferSizes.split(",");
3287 }
3288
3289 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3290
3291 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003292 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003293
Chenbo Feng15416292018-11-08 17:36:21 -08003294 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3295 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3296 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003297 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003298 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003299 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003300 }
3301 }
3302
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003303 @Override
3304 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003305 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003306 NETWORK_RESTORE_DELAY_PROP_NAME);
3307 if(restoreDefaultNetworkDelayStr != null &&
3308 restoreDefaultNetworkDelayStr.length() != 0) {
3309 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003310 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003311 } catch (NumberFormatException e) {
3312 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003313 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003314 // if the system property isn't set, use the value for the apn type
3315 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3316
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003317 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3318 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003319 }
3320 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003321 }
3322
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003323 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003324 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003325 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003326 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003327 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003328 // Start gathering diagnostic information.
3329 netDiags.add(new NetworkDiagnostics(
3330 nai.network,
3331 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003332 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003333 DIAG_TIME_MS));
3334 }
3335
3336 for (NetworkDiagnostics netDiag : netDiags) {
3337 pw.println();
3338 netDiag.waitForMeasurements();
3339 netDiag.dump(pw);
3340 }
3341 }
3342
The Android Open Source Project28527d22009-03-03 19:31:44 -08003343 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003344 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3345 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003346 if (!checkDumpPermission(mContext, TAG, writer)) return;
3347
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003348 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003349 }
3350
lucaslin99473f62020-12-10 15:10:54 +08003351 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3352 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3353 != PackageManager.PERMISSION_GRANTED) {
3354 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003355 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003356 + " due to missing android.permission.DUMP permission");
3357 return false;
3358 } else {
3359 return true;
3360 }
3361 }
3362
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003363 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003364 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003365
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003366 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003367 dumpNetworkDiagnostics(pw);
3368 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003369 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003370 dumpNetworks(pw);
3371 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003372 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003373 dumpNetworkRequests(pw);
3374 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003375 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3376 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3377 dumpTrafficController(pw, fd, verbose);
3378 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003379 }
Erik Kline9647f382015-06-05 17:47:34 +09003380
Junyu Lai0da479b2022-04-20 15:06:29 +08003381 pw.println("NetworkProviders for:");
3382 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003383 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003384 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003385 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003386 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003387 pw.println();
3388
Chalard Jean5b409c72021-02-04 13:12:59 +09003389 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003390 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003391 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003392 pw.println("none");
3393 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003394 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003395 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003396 pw.println();
3397
James Mattis8b298a02021-06-01 22:34:04 -07003398 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003399 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003400 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003401 pw.decreaseIndent();
3402 pw.println();
3403
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003404 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003405 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003406 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003407 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003408 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003409
junyulaif2c67e42018-08-07 19:50:45 +08003410 pw.println("Status for known UIDs:");
3411 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003412 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003413 for (int i = 0; i < size; i++) {
3414 // Don't crash if the array is modified while dumping in bugreports.
3415 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003416 final int uid = mUidBlockedReasons.keyAt(i);
3417 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3418 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003419 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003420 } catch (ArrayIndexOutOfBoundsException e) {
3421 pw.println(" ArrayIndexOutOfBoundsException");
3422 } catch (ConcurrentModificationException e) {
3423 pw.println(" ConcurrentModificationException");
3424 }
3425 }
3426 pw.println();
3427 pw.decreaseIndent();
3428
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003429 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003430 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003431 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003432 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003433 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003434
Junyu Lai0da479b2022-04-20 15:06:29 +08003435 pw.println("Network Offers:");
3436 pw.increaseIndent();
3437 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3438 pw.println(offerInfo.offer);
3439 }
3440 pw.decreaseIndent();
3441 pw.println();
3442
Robert Greenwalt94e22142014-07-30 16:31:24 -07003443 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003444
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003445 pw.println();
markchien5e866652019-09-30 14:40:57 +08003446 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003447
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003448 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003449 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003450
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003451 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003452
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003453 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003454 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003455 pw.println("mNetworkRequestInfoLogs (most recent first):");
3456 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003457 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003458 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003459
3460 pw.println();
3461 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3462 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003463 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003464 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003465
3466 pw.println();
3467 pw.println("NetTransition WakeLock activity (most recent first):");
3468 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003469 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3470 pw.println("total releases: " + mTotalWakelockReleases);
3471 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3472 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3473 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3474 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3475 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3476 }
James Mattiscb1e0362021-04-06 17:07:42 -07003477 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003478
3479 pw.println();
3480 pw.println("bandwidth update requests (by uid):");
3481 pw.increaseIndent();
3482 synchronized (mBandwidthRequests) {
3483 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3484 pw.println("[" + mBandwidthRequests.keyAt(i)
3485 + "]: " + mBandwidthRequests.valueAt(i));
3486 }
3487 }
3488 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003489 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003490
James Mattiscb1e0362021-04-06 17:07:42 -07003491 pw.println();
3492 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3493 pw.increaseIndent();
3494 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003495 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003496 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003497
3498 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003499
3500 pw.println();
3501 pw.println("Permission Monitor:");
3502 pw.increaseIndent();
3503 mPermissionMonitor.dump(pw);
3504 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003505
3506 pw.println();
3507 pw.println("Legacy network activity:");
3508 pw.increaseIndent();
3509 mNetworkActivityTracker.dump(pw);
3510 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003511 }
3512
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003513 private void dumpNetworks(IndentingPrintWriter pw) {
3514 for (NetworkAgentInfo nai : networksSortedById()) {
3515 pw.println(nai.toString());
3516 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003517 pw.println("Nat464Xlat:");
3518 pw.increaseIndent();
3519 nai.dumpNat464Xlat(pw);
3520 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003521 pw.println(String.format(
3522 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3523 nai.numForegroundNetworkRequests(),
3524 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3525 nai.numBackgroundNetworkRequests(),
3526 nai.numNetworkRequests()));
3527 pw.increaseIndent();
3528 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3529 pw.println(nai.requestAt(i).toString());
3530 }
3531 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003532 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003533 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003534 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003535 pw.decreaseIndent();
3536 pw.decreaseIndent();
3537 }
3538 }
3539
James Mattis8b298a02021-06-01 22:34:04 -07003540 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3541 if (!mProfileNetworkPreferences.isEmpty()) {
3542 pw.println("Profile preferences:");
3543 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003544 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003545 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003546 }
James Mattis8b298a02021-06-01 22:34:04 -07003547 if (!mOemNetworkPreferences.isEmpty()) {
3548 pw.println("OEM preferences:");
3549 pw.increaseIndent();
3550 pw.println(mOemNetworkPreferences);
3551 pw.decreaseIndent();
3552 }
3553 if (!mMobileDataPreferredUids.isEmpty()) {
3554 pw.println("Mobile data preferred UIDs:");
3555 pw.increaseIndent();
3556 pw.println(mMobileDataPreferredUids);
3557 pw.decreaseIndent();
3558 }
James Mattis45d81842021-01-10 14:24:24 -08003559
James Mattis8b298a02021-06-01 22:34:04 -07003560 pw.println("Default requests:");
3561 pw.increaseIndent();
3562 dumpPerAppDefaultRequests(pw);
3563 pw.decreaseIndent();
3564 }
3565
3566 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003567 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3568 if (mDefaultRequest == defaultRequest) {
3569 continue;
3570 }
3571
James Mattis8b298a02021-06-01 22:34:04 -07003572 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3573 final String networkOutput;
3574 if (null == satisfier) {
3575 networkOutput = "null";
3576 } else if (mNoServiceNetwork.equals(satisfier)) {
3577 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003578 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003579 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003580 }
James Mattis8b298a02021-06-01 22:34:04 -07003581 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3582 ? "" : " asUid: " + defaultRequest.mAsUid;
3583 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3584 + defaultRequest.mPid + asUidString + "]";
3585 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3586 + " Preference order: " + defaultRequest.mPreferenceOrder
3587 + " Tracked UIDs: " + defaultRequest.getUids();
3588 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003589 }
3590 }
3591
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003592 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003593 NetworkRequestInfo[] infos = null;
3594 while (infos == null) {
3595 try {
3596 infos = requestsSortedById();
3597 } catch (ConcurrentModificationException e) {
3598 // mNetworkRequests should only be accessed from handler thread, except dump().
3599 // As dump() is never called in normal usage, it would be needlessly expensive
3600 // to lock the collection only for its benefit. Instead, retry getting the
3601 // requests if ConcurrentModificationException is thrown during dump().
3602 }
3603 }
3604 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003605 pw.println(nri.toString());
3606 }
3607 }
3608
Ken Chene6d511f2022-01-25 11:10:42 +08003609 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3610 boolean verbose) {
3611 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003612 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003613 } catch (ServiceSpecificException e) {
3614 pw.println(e.getMessage());
3615 } catch (IOException e) {
3616 loge("Dump BPF maps failed, " + e);
3617 }
3618 }
3619
Chalard Jean524f0b12021-10-25 21:11:56 +09003620 private void dumpAllRequestInfoLogsToLogcat() {
3621 try (PrintWriter logPw = new PrintWriter(new Writer() {
3622 @Override
3623 public void write(final char[] cbuf, final int off, final int len) {
3624 // This method is called with 0-length and 1-length arrays for empty strings
3625 // or strings containing only the DEL character.
3626 if (len <= 1) return;
3627 Log.e(TAG, new String(cbuf, off, len));
3628 }
3629 @Override public void flush() {}
3630 @Override public void close() {}
3631 })) {
3632 mNetworkRequestInfoLogs.dump(logPw);
3633 }
3634 }
3635
Hugo Benichia480ba52018-09-03 08:19:02 +09003636 /**
3637 * Return an array of all current NetworkAgentInfos sorted by network id.
3638 */
3639 private NetworkAgentInfo[] networksSortedById() {
3640 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003641 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003642 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003643 return networks;
3644 }
3645
3646 /**
3647 * Return an array of all current NetworkRequest sorted by request id.
3648 */
James Mattis258ea3c2020-11-15 15:04:40 -08003649 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003650 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003651 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003652 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003653 // Sort the array based off the NRI containing the min requestId in its requests.
3654 Arrays.sort(requests,
3655 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3656 Comparator.comparingInt(req -> req.requestId)).requestId
3657 )
3658 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003659 return requests;
3660 }
3661
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003662 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003663 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003664 if (officialNai != null && officialNai.equals(nai)) return true;
3665 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003666 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003667 " - " + nai);
3668 }
3669 return false;
3670 }
3671
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003672 private boolean isDisconnectRequest(Message msg) {
3673 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3674 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3675 return info.getState() == NetworkInfo.State.DISCONNECTED;
3676 }
3677
Robert Greenwalt2034b912009-08-12 16:08:25 -07003678 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003679 private class NetworkStateTrackerHandler extends Handler {
3680 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003681 super(looper);
3682 }
3683
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003684 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003685 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3686 final NetworkAgentInfo nai = arg.first;
3687 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003688 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003689 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003690 }
3691 return;
3692 }
3693
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003694 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003695 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003696 return;
3697 }
3698
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003699 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003700 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003701 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3702 final NetworkCapabilities sanitized =
3703 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003704 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003705 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003706 break;
3707 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003708 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003709 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003710 processLinkPropertiesFromAgent(nai, newLp);
3711 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003712 break;
3713 }
3714 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003715 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003716 updateNetworkInfo(nai, info);
3717 break;
3718 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003719 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003720 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003721 break;
3722 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003723 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003724 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003725 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003726 // Note that if the NAI had been connected, this would affect the
3727 // score, and therefore would require re-mixing the score and performing
3728 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003729 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003730 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3731 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003732 // Mark the network as temporarily accepting partial connectivity so that it
3733 // will be validated (and possibly become default) even if it only provides
3734 // partial internet access. Note that if user connects to partial connectivity
3735 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3736 // out of wifi coverage) and if the same wifi is available again, the device
3737 // will auto connect to this wifi even though the wifi has "no internet".
3738 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003739 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003740 break;
3741 }
junyulai011b1f12019-01-03 18:50:15 +08003742 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003743 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003744 break;
3745 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003746 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003747 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003748 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003749
3750 if (isLegacyLockdownNai(nai)
3751 && (underlying == null || underlying.size() != 1)) {
3752 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3753 + " must have exactly one underlying network: " + underlying);
3754 }
3755
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003756 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3757 nai.declaredUnderlyingNetworks = (underlying != null)
3758 ? underlying.toArray(new Network[0]) : null;
3759
3760 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3761 if (DBG) {
3762 log(nai.toShortString() + " changed underlying networks to "
3763 + Arrays.toString(nai.declaredUnderlyingNetworks));
3764 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003765 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003766 notifyIfacesChangedForNetworkStats();
3767 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003768 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003769 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003770 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3771 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3772 nai.teardownDelayMs = msg.arg1;
3773 } else {
3774 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3775 }
Chalard Jean550b5212021-03-05 23:07:53 +09003776 break;
3777 }
3778 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3779 nai.setLingerDuration((int) arg.second);
3780 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003781 }
Tyler Wear72388212021-09-09 14:49:02 -07003782 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3783 DscpPolicy policy = (DscpPolicy) arg.second;
3784 if (mDscpPolicyTracker != null) {
3785 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3786 }
3787 break;
3788 }
3789 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3790 if (mDscpPolicyTracker != null) {
3791 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3792 }
3793 break;
3794 }
3795 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3796 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003797 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003798 }
3799 break;
3800 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003801 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09003802 if (!nai.isCreated()) {
3803 Log.d(TAG, "unregisterAfterReplacement on uncreated " + nai.toShortString()
3804 + ", tearing down instead");
3805 teardownUnneededNetwork(nai);
3806 break;
3807 }
3808
3809 if (nai.isDestroyed()) {
3810 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
3811 + ", ignoring");
3812 break;
3813 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003814
3815 final int timeoutMs = (int) arg.second;
3816 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3817 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3818 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3819 }
3820
3821 // Marking a network awaiting replacement is used to ensure that any requests
3822 // satisfied by the network do not switch to another network until a
3823 // replacement is available or the wait for a replacement times out.
3824 // If the network is inactive (i.e., nascent or lingering), then there are no
3825 // such requests, and there is no point keeping it. Just tear it down.
3826 // Note that setLingerDuration(0) cannot be used to do this because the network
3827 // could be nascent.
3828 nai.clearInactivityState();
3829 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3830 Log.d(TAG, nai.toShortString()
3831 + " marked awaiting replacement is unneeded, tearing down instead");
3832 teardownUnneededNetwork(nai);
3833 break;
3834 }
3835
3836 Log.d(TAG, "Marking " + nai.toShortString()
3837 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3838 destroyNativeNetwork(nai);
3839
3840 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3841 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3842 // consider the fact that the network could already have disconnected or been
3843 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3844 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3845 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3846 mKeepaliveTracker.handleStopAllKeepalives(nai,
3847 SocketKeepalive.ERROR_INVALID_NETWORK);
3848
3849 nai.updateScoreForNetworkAgentUpdate();
3850 // This rematch is almost certainly not going to result in any changes, because
3851 // the destroyed flag is only just above the "current satisfier wins"
3852 // tie-breaker. But technically anything that affects scoring should rematch.
3853 rematchAllNetworksAndRequests();
3854 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3855 break;
3856 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003857 }
3858 }
3859
3860 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003861 final int netId = msg.arg2;
3862 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003863 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003864 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003865 switch (msg.what) {
3866 default:
3867 return false;
lucasline117e2e2019-10-22 18:27:33 +08003868 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003869 if (nai == null) {
3870 break;
3871 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003872 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3873 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003874 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003875 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003876 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003877 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003878 if (probePrivateDnsCompleted) {
3879 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3880 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003881 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003882 }
3883 // Only show the notification when the private DNS is broken and the
3884 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003885 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003886 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3887 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003888 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003889 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3890 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3891 // private DNS is broken, it means this network is being reevaluated.
3892 // Either probing private DNS is not necessary any more or it hasn't been
3893 // done yet. In either case, the networkCapabilities should be updated to
3894 // reflect the new status.
3895 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003896 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003897 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003898 }
3899 break;
3900 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003901 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003902 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3903
Erik Kline31b4a9e2018-01-11 21:07:29 +09003904 if (nai == null) break;
3905
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003906 handleNetworkTested(nai, results.mTestResult,
3907 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003908 break;
3909 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003910 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003911 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003912 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003913 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003914 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003915 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003916 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3917 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003918 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003919 if (nai == null) {
3920 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3921 break;
3922 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003923 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003924 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003925 (PendingIntent) msg.obj,
3926 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003927 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003928 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003929 break;
3930 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003931 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003932 if (nai == null) break;
3933
Erik Kline9a62f012018-03-21 07:18:33 -07003934 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003935 break;
3936 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003937 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003938 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003939 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003940 break;
3941 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003942 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003943 return true;
3944 }
3945
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003946 private void handleNetworkTested(
3947 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09003948 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
3949 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09003950 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003951
3952 // If there is any kind of working networking, then the NAI has been evaluated
3953 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
3954 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09003955 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003956 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09003957 // Because of b/245893397, if the score is updated when updateCapabilities is called,
3958 // any callback that receives onAvailable for that rematch receives an extra caps
3959 // callback. To prevent that, update the score in the agent so the updates below won't
3960 // see an update to both caps and score at the same time.
3961 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003962 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
3963
he_won.hwang881307a2022-03-15 21:23:52 +09003964 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3965 // Assume the validation failure is due to a temporary failure after roaming
3966 // and ignore it. NetworkMonitor will continue to retry validation. If it
3967 // continues to fail after the block timeout expires, the network will be
3968 // marked unvalidated. If it succeeds, then validation state will not change.
3969 return;
3970 }
3971
Chalard Jean254bd162022-08-25 13:04:51 +09003972 final boolean wasValidated = nai.isValidated();
3973 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09003974 final boolean wasPortal = nai.captivePortalDetected();
3975 nai.setPartialConnectivity(partial);
3976 nai.setCaptivePortalDetected(portal);
3977 nai.updateScoreForNetworkAgentUpdate();
3978 final boolean partialConnectivityChanged = (wasPartial != partial);
3979 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003980
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003981 if (DBG) {
3982 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3983 ? " with redirect to " + redirectUrl
3984 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003985 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003986 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09003987 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003988 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003989 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003990 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003991 if (valid) {
3992 handleFreshlyValidatedNetwork(nai);
3993 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3994 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003995 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003996 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003997 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003998 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003999 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004000 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004001 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004002 NotificationType.PRIVATE_DNS_BROKEN);
4003 // If network becomes valid, the hasShownBroken should be reset for
4004 // that network so that the notification will be fired when the private
4005 // DNS is broken again.
4006 nai.networkAgentConfig.hasShownBroken = false;
4007 }
4008 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004009 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004010 } else if (portalChanged) {
4011 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
4012 == getCaptivePortalMode()) {
4013 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4014 nai.onPreventAutomaticReconnect();
4015 teardownUnneededNetwork(nai);
4016 return;
4017 } else {
4018 updateCapabilitiesForNetwork(nai);
4019 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004020 } else if (becameEvaluated) {
4021 // If valid or partial connectivity changed, updateCapabilities* has
4022 // done the rematch.
4023 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004024 }
4025 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004026
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004027 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004028 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004029 nai.onValidationStatusChanged(
4030 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4031 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004032
4033 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004034 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004035 // immediately. Re-notify partial connectivity silently if no internet
4036 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004037 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004038 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004039 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4040 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004041 }
4042
Chalard Jean254bd162022-08-25 13:04:51 +09004043 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004044 handleNetworkUnvalidated(nai);
4045 }
4046 }
4047
Calvin Ondada1452016-10-11 15:10:46 -07004048 private int getCaptivePortalMode() {
4049 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004050 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4051 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004052 }
4053
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004054 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4055 switch (msg.what) {
4056 default:
4057 return false;
4058 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4059 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4060 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4061 handleLingerComplete(nai);
4062 }
4063 break;
4064 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004065 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4066 handleNetworkAgentRegistered(msg);
4067 break;
4068 }
4069 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4070 handleNetworkAgentDisconnected(msg);
4071 break;
4072 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004073 }
4074 return true;
4075 }
4076
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004077 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004078 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004079 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004080 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004081 maybeHandleNetworkAgentMessage(msg);
4082 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004083 }
4084 }
4085
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004086 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004087 private final int mNetId;
4088 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004089
4090 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004091 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004092 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004093 }
4094
4095 @Override
4096 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4097 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004098 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004099 }
4100
4101 @Override
4102 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004103 // Legacy version of notifyNetworkTestedWithExtras.
4104 // Would only be called if the system has a NetworkStack module older than the
4105 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004106 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004107 }
4108
4109 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004110 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004111 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4112 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004113 final Message msg = mTrackerHandler.obtainMessage(
4114 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004115 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004116 new NetworkTestedResults(
4117 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004118 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004119
4120 // Invoke ConnectivityReport generation for this Network test event.
4121 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4122 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004123
Cody Kestingf1120be2020-08-03 18:01:40 -07004124 // NetworkMonitor reports the network validation result as a bitmask while
4125 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4126 // logical value for ConnectivityDiagnostics.
4127 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4128 p.result);
4129
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004130 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004131 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004132 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4133 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4134
Aaron Huang959d3642021-01-21 15:47:41 +08004135 ConnectivityReportEvent reportEvent =
4136 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4137 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004138 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004139 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004140 }
4141
4142 @Override
4143 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4144 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4145 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004146 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004147 }
4148
4149 @Override
lucasline117e2e2019-10-22 18:27:33 +08004150 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4151 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4152 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004153 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004154 }
4155
4156 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004157 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4158 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4159 EVENT_CAPPORT_DATA_CHANGED,
4160 0, mNetId, data));
4161 }
4162
4163 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004164 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004165 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004166 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004167
4168 final PendingIntent pendingIntent;
4169 // Only the system server can register notifications with package "android"
4170 final long token = Binder.clearCallingIdentity();
4171 try {
paulhu7746e4e2020-06-09 19:07:03 +08004172 pendingIntent = PendingIntent.getBroadcast(
4173 mContext,
4174 0 /* requestCode */,
4175 intent,
4176 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004177 } finally {
4178 Binder.restoreCallingIdentity(token);
4179 }
4180 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4181 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004182 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004183 }
4184
4185 @Override
4186 public void hideProvisioningNotification() {
4187 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004188 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004189 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004190
4191 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004192 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004193 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004194 }
4195
4196 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004197 public int getInterfaceVersion() {
4198 return this.VERSION;
4199 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004200
4201 @Override
4202 public String getInterfaceHash() {
4203 return this.HASH;
4204 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004205 }
4206
Cody Kestingf1120be2020-08-03 18:01:40 -07004207 /**
4208 * Converts the given NetworkMonitor-specific validation result bitmask to a
4209 * ConnectivityDiagnostics-specific validation result int.
4210 */
4211 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4212 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4213 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4214 }
4215 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4216 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4217 }
4218 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4219 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4220 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4221 }
4222
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004223 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004224 log("Data stall detected with methods: " + p.detectionMethod);
4225
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004226 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004227 int detectionMethod = 0;
4228 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4229 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4230 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4231 }
4232 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4233 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4234 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4235 p.tcpMetricsCollectionPeriodMillis);
4236 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004237 }
4238
Cody Kestingf53a0752020-04-15 12:33:28 -07004239 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004240 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004241 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004242
4243 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4244 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4245 // the cost of going through two handlers.
4246 mConnectivityDiagnosticsHandler.sendMessage(msg);
4247 }
4248
Cody Kestingb37958e2020-05-15 10:36:01 -07004249 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4250 return (p.detectionMethod & detectionMethod) != 0;
4251 }
4252
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004253 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4254 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004255 }
4256
Erik Klinea73af002018-06-26 18:53:43 +09004257 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4258 if (nai == null) return;
4259 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4260 // in order to restart a validation pass from within netd.
4261 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4262 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004263 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004264 }
4265 }
4266
Erik Kline31b4a9e2018-01-11 21:07:29 +09004267 private void handlePrivateDnsSettingsChanged() {
4268 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4269
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004270 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004271 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004272 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004273 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4274 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004275 }
4276 }
4277
Erik Kline9a62f012018-03-21 07:18:33 -07004278 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4279 // Private DNS only ever applies to networks that might provide
4280 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004281 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004282
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004283 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004284 // schedule DNS resolutions. If a DNS resolution is required the
4285 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004286 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004287
4288 // With Private DNS bypass support, we can proceed to update the
4289 // Private DNS config immediately, even if we're in strict mode
4290 // and have not yet resolved the provider name into a set of IPs.
4291 updatePrivateDns(nai, cfg);
4292 }
4293
4294 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4295 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004296 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004297 }
4298
dalyk1720e542018-03-05 12:42:22 -05004299 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4300 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4301 if (nai == null) {
4302 return;
4303 }
4304 mDnsManager.updatePrivateDnsValidation(update);
4305 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4306 }
4307
paulhu7c0a2e62021-01-08 00:51:49 +08004308 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004309 int prefixLength) {
4310 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4311 if (nai == null) return;
4312
paulhu7c0a2e62021-01-08 00:51:49 +08004313 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4314 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004315
4316 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004317 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004318 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004319 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004320 prefixLength);
4321 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004322 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004323 return;
4324 }
4325 }
4326
Lorenzo Colittid523d142020-04-01 20:16:30 +09004327 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004328 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4329 }
4330
Hai Shalome58bdc62021-01-11 18:45:34 -08004331 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004332 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004333 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004334 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4335 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4336 }
4337
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004338 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004339 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004340 * @param nai the agent info to update
4341 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004342 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004343 */
junyulai2b6f0c22021-02-03 20:15:30 +08004344 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4345 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4346 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004347 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004348 // one lingered request, set inactive.
4349 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004350 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004351 if (DBG) log("Unsetting inactive " + nai.toShortString());
4352 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004353 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004354 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004355 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004356 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4357 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004358 }
junyulai2b6f0c22021-02-03 20:15:30 +08004359 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004360 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004361 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004362 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004363 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004364 }
4365
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004366 private void handleNetworkAgentRegistered(Message msg) {
4367 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4368 if (!mNetworkAgentInfos.contains(nai)) {
4369 return;
4370 }
4371
4372 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4373 if (VDBG) log("NetworkAgent registered");
4374 } else {
4375 loge("Error connecting NetworkAgent");
4376 mNetworkAgentInfos.remove(nai);
4377 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004378 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004379 synchronized (mNetworkForNetId) {
4380 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004381 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004382 mNetIdManager.releaseNetId(nai.network.getNetId());
4383 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004384 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004385 }
4386 }
4387 }
Paul Jensend5f53392014-11-25 15:26:53 -05004388
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004389 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004390 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004391 }
4392
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004393 @VisibleForTesting
4394 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004395 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004396 if (SdkLevel.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004397
4398 // If the network never roamed, return false. The check below is not sufficient if time
4399 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4400 if (nai.lastRoamTime == 0) return false;
4401
he_won.hwang881307a2022-03-15 21:23:52 +09004402 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4403 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004404 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004405 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004406 final long currentTimeMs = SystemClock.elapsedRealtime();
4407 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004408 if (timeSinceLastRoam <= blockTimeOut) {
4409 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4410 return true;
4411 }
4412 }
4413 return false;
4414 }
4415
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004416 private void handleNetworkAgentDisconnected(Message msg) {
4417 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004418 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004419 }
4420
Chalard Jeand9fffc32018-05-11 20:19:20 +09004421 // Destroys a network, remove references to it from the internal state managed by
4422 // ConnectivityService, free its interfaces and clean up.
4423 // Must be called on the Handler thread.
4424 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004425 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004426
4427 if (!mNetworkAgentInfos.contains(nai)) return;
4428
Chalard Jeand9fffc32018-05-11 20:19:20 +09004429 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004430 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004431 }
lucaslinb25c9a62019-02-12 15:30:13 +08004432 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004433 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004434 // A network agent has disconnected.
4435 // TODO - if we move the logic to the network agent (have them disconnect
4436 // because they lost all their requests or because their score isn't good)
4437 // then they would disconnect organically, report their new state and then
4438 // disconnect the channel.
4439 if (nai.networkInfo.isConnected()) {
4440 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4441 null, null);
4442 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004443 final boolean wasDefault = isDefaultNetwork(nai);
4444 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004445 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004446 }
4447 notifyIfacesChangedForNetworkStats();
4448 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4449 // by other networks that are already connected. Perhaps that can be done by
4450 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4451 // of rematchAllNetworksAndRequests
4452 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004453 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004454
4455 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004456 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4457 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004458 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004459 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004460 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004461 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004462 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004463 synchronized (mNetworkForNetId) {
4464 // Remove the NetworkAgent, but don't mark the netId as
4465 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004466 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004467 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004468 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004469 // Update allowed network lists in netd. This should be called after removing nai
4470 // from mNetworkAgentInfos.
4471 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004472 // Remove all previously satisfied requests.
4473 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004474 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004475 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004476 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004477 if (currentNetwork != null
4478 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004479 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004480 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4481 // rematch not to keep disconnected agents instead of setting it here ; this
4482 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004483 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004484 for (final NetworkOfferInfo noi : mNetworkOffers) {
4485 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004486 }
James Mattise3ef1912020-12-20 11:09:58 -08004487
Chalard Jean5b409c72021-02-04 13:12:59 +09004488 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004489 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004490 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004491 // network, because while incorrect this is the closest to the old (also
4492 // incorrect) behavior.
4493 mNetworkActivityTracker.updateDataActivityTracking(
4494 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004495 ensureNetworkTransitionWakelock(nai.toShortString());
4496 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004497 }
4498 }
junyulai2b6f0c22021-02-03 20:15:30 +08004499 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004500 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004501 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004502 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004503 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004504 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004505 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004506
4507 // Immediate teardown.
4508 if (nai.teardownDelayMs == 0) {
4509 destroyNetwork(nai);
4510 return;
4511 }
4512
4513 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004514 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304515 try {
4516 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4517 } catch (RemoteException e) {
4518 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4519 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004520 }
4521 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4522 }
4523
4524 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004525 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004526 // Tell netd to clean up the configuration for this network
4527 // (routing rules, DNS, etc).
4528 // This may be slow as it requires a lot of netd shelling out to ip and
4529 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004530 // after we've rematched networks with requests (which might change the default
4531 // network or service a new request from an app), so network traffic isn't interrupted
4532 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004533 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004534 }
Chalard Jean254bd162022-08-25 13:04:51 +09004535 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004536 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4537 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4538 // false if the network was never created.
4539 // TODO: delete when S is no longer supported.
4540 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004541 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004542 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004543 }
4544
Ken Chen6df7a902021-04-09 15:08:42 +08004545 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004546 try {
4547 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004548 final NativeNetworkConfig config;
4549 if (nai.isVPN()) {
4550 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004551 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004552 return false;
4553 }
4554 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4555 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004556 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004557 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004558 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004559 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004560 getNetworkPermission(nai.networkCapabilities),
4561 false /* secure */,
4562 VpnManager.TYPE_VPN_NONE,
4563 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004564 }
Ken Chen6df7a902021-04-09 15:08:42 +08004565 mNetd.networkCreate(config);
4566 mDnsResolver.createNetworkCache(nai.network.getNetId());
4567 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4568 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004569 return true;
4570 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004571 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004572 return false;
4573 }
4574 }
4575
Ken Chen6df7a902021-04-09 15:08:42 +08004576 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004577 if (mDscpPolicyTracker != null) {
4578 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4579 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004580 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004581 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004582 } catch (RemoteException | ServiceSpecificException e) {
4583 loge("Exception destroying network(networkDestroy): " + e);
4584 }
4585 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004586 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004587 } catch (RemoteException | ServiceSpecificException e) {
4588 loge("Exception destroying network: " + e);
4589 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004590 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4591 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4592 // gets created, could add data to DnsManager data structures that will never get deleted.
4593 mDnsManager.removeNetwork(nai.network);
4594
4595 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004596 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004597 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4598 }
4599
Chalard Jean254bd162022-08-25 13:04:51 +09004600 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004601 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004602 }
4603
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004604 // If this method proves to be too slow then we can maintain a separate
4605 // pendingIntent => NetworkRequestInfo map.
4606 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4607 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004608 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4609 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4610 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004611 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004612 return entry.getValue();
4613 }
4614 }
4615 return null;
4616 }
4617
Chalard Jean524f0b12021-10-25 21:11:56 +09004618 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4619 if (SdkLevel.isAtLeastT()) {
4620 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4621 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4622 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4623 // bug is fixed.
4624 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004625 throw new IllegalStateException("This NRI is already registered. New : " + nri
4626 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004627 }
4628 }
4629 }
4630 }
4631
Chalard Jeanac9ace02022-01-26 16:54:05 +09004632 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4633 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004634 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004635 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4636 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004637 }
4638 return false;
4639 }
4640
James Mattisf7027322020-12-13 16:28:14 -08004641 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004642 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004643 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4644 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4645 final NetworkRequestInfo existingRequest =
4646 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004647 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004648 if (DBG) {
4649 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4650 + nri.mRequests.get(0) + " because their intents matched.");
4651 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004652 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004653 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004654 }
Erik Kline05f2b402015-04-30 12:58:40 +09004655 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004656 }
4657
James Mattisf7027322020-12-13 16:28:14 -08004658 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004659 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004660 }
4661
James Mattis3ce3d3c2021-02-09 18:18:28 -08004662 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004663 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004664 for (final NetworkRequestInfo nri : nris) {
4665 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004666 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004667 for (final NetworkRequest req : nri.mRequests) {
4668 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004669 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004670 if (req.isListen()) {
4671 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4672 if (req.networkCapabilities.hasSignalStrength()
4673 && network.satisfiesImmutableCapabilitiesOf(req)) {
4674 updateSignalStrengthThresholds(network, "REGISTER", req);
4675 }
James Mattisf7027322020-12-13 16:28:14 -08004676 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004677 }
4678 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004679
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004680 // If this NRI has a satisfier already, it is replacing an older request that
4681 // has been removed. Track it.
4682 final NetworkRequest activeRequest = nri.getActiveRequest();
4683 if (null != activeRequest) {
4684 // If there is an active request, then for sure there is a satisfier.
4685 nri.getSatisfier().addRequest(activeRequest);
4686 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004687 }
James Mattisf7027322020-12-13 16:28:14 -08004688
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004689 if (mFlags.noRematchAllRequestsOnRegister()) {
4690 rematchNetworksAndRequests(nris);
4691 } else {
4692 rematchAllNetworksAndRequests();
4693 }
James Mattis45d81842021-01-10 14:24:24 -08004694
Chalard Jean0354d8c2021-01-12 10:58:56 +09004695 // Requests that have not been matched to a network will not have been sent to the
4696 // providers, because the old satisfier and the new satisfier are the same (null in this
4697 // case). Send these requests to the providers.
4698 for (final NetworkRequestInfo nri : nris) {
4699 for (final NetworkOfferInfo noi : mNetworkOffers) {
4700 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004701 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004702 }
4703 }
4704
James Mattisf7027322020-12-13 16:28:14 -08004705 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4706 final int callingUid) {
4707 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004708 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004709 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4710 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4711 handleReleaseNetworkRequest(
4712 nri.mRequests.get(0),
4713 callingUid,
4714 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004715 }
4716 }
4717
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004718 // Determines whether the network is the best (or could become the best, if it validated), for
4719 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4720 // on the value of reason:
4721 //
4722 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4723 // then it should be torn down.
4724 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4725 // then it should be lingered.
4726 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004727 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004728
Chalard Jean254bd162022-08-25 13:04:51 +09004729 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004730 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4731 return false;
4732 }
4733
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004734 final int numRequests;
4735 switch (reason) {
4736 case TEARDOWN:
4737 numRequests = nai.numRequestNetworkRequests();
4738 break;
4739 case LINGER:
4740 numRequests = nai.numForegroundNetworkRequests();
4741 break;
4742 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004743 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004744 return true;
4745 }
4746
Chalard Jean947acd42021-03-08 22:29:27 +09004747 if (numRequests > 0) return false;
4748
Paul Jensende49eb12015-06-25 15:30:08 -04004749 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004750 if (reason == UnneededFor.LINGER
4751 && !nri.isMultilayerRequest()
4752 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004753 // Background requests don't affect lingering.
4754 continue;
4755 }
4756
James Mattis3d229892020-11-16 16:46:28 -08004757 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004758 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004759 }
4760 }
Paul Jensende49eb12015-06-25 15:30:08 -04004761 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004762 }
4763
James Mattis3d229892020-11-16 16:46:28 -08004764 private boolean isNetworkPotentialSatisfier(
4765 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4766 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004767 // request, return immediately. For multilayer requests, check to see if any of the
4768 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004769 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4770 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004771 return false;
4772 }
4773 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004774 // This multilayer listen request is satisfied therefore no further requests need to be
4775 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004776 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004777 return false;
4778 }
James Mattis3d229892020-11-16 16:46:28 -08004779 // As non-multilayer listen requests have already returned, the below would only happen
4780 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004781 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004782 continue;
4783 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004784 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004785 // there is hope for it to become one if it validated, then it is needed.
4786 if (candidate.satisfies(req)) {
4787 // As soon as a network is found that satisfies a request, return. Specifically for
4788 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4789 // is important so as to not evaluate lower priority requests further in
4790 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004791 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4792 ? nri.getSatisfier() : null;
4793 // Note that this catches two important cases:
4794 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4795 // is currently satisfying the request. This is desirable when
4796 // cellular ends up validating but WiFi does not.
4797 // 2. Unvalidated WiFi will not be reaped when validated cellular
4798 // is currently satisfying the request. This is desirable when
4799 // WiFi ends up validating and out scoring cellular.
4800 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004801 }
4802 }
4803
4804 return false;
4805 }
4806
Erik Kline0c04b742016-07-07 16:50:58 +09004807 private NetworkRequestInfo getNriForAppRequest(
4808 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004809 // Looking up the app passed param request in mRequests isn't possible since it may return
4810 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4811 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004812 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4813 // to avoid potential race conditions when validating a package->uid mapping when sending
4814 // the callback on the very low-chance that an application shuts down prior to the callback
4815 // being sent.
4816 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4817 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004818
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004819 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004820 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004821 log(String.format("UID %d attempted to %s for unowned request %s",
4822 callingUid, requestedOperation, nri));
4823 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004824 }
Erik Kline0c04b742016-07-07 16:50:58 +09004825 }
4826
4827 return nri;
4828 }
4829
James Mattisf7027322020-12-13 16:28:14 -08004830 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4831 final String callingMethod) {
4832 if (nri.isMultilayerRequest()) {
4833 throw new IllegalStateException(
4834 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004835 }
4836 }
4837
James Mattisf7027322020-12-13 16:28:14 -08004838 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004839 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004840 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4841 // single NetworkRequest and thus does not apply to multilayer requests.
4842 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4843 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004844 return;
4845 }
James Mattis2516da32021-01-31 17:06:19 -08004846 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004847 return;
4848 }
James Mattisf7027322020-12-13 16:28:14 -08004849 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4850 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004851 }
4852 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004853 callCallbackForRequest(
4854 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004855 }
4856
James Mattisf7027322020-12-13 16:28:14 -08004857 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4858 final int callingUid,
4859 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004860 final NetworkRequestInfo nri =
4861 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4862 if (nri == null) {
4863 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004864 }
James Mattisf7027322020-12-13 16:28:14 -08004865 if (VDBG || (DBG && request.isRequest())) {
4866 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004867 }
4868 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004869 if (callOnUnavailable) {
4870 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4871 }
Erik Kline155a59a2015-11-25 12:49:38 +09004872 }
Erik Kline0c04b742016-07-07 16:50:58 +09004873
James Mattisa076c532020-12-02 14:12:41 -08004874 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004875 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004876 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004877 if (null == mNetworkRequests.remove(req)) {
4878 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4879 continue;
4880 }
James Mattisa076c532020-12-02 14:12:41 -08004881 if (req.isListen()) {
4882 removeListenRequestFromNetworks(req);
4883 }
4884 }
James Mattis8f036802021-06-20 16:26:01 -07004885 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004886 if (mDefaultNetworkRequests.remove(nri)) {
4887 // If this request was one of the defaults, then the UID rules need to be updated
4888 // WARNING : if the app(s) for which this network request is the default are doing
4889 // traffic, this will kill their connected sockets, even if an equivalent request
4890 // is going to be reinstated right away ; unconnected traffic will go on the default
4891 // until the new default is set, which will happen very soon.
4892 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4893 // remove ranges for those requests that won't have a replacement
4894 final NetworkAgentInfo satisfier = nri.getSatisfier();
4895 if (null != satisfier) {
4896 try {
paulhu0e79d952021-06-09 16:11:35 +08004897 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4898 satisfier.network.getNetId(),
4899 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004900 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004901 } catch (RemoteException e) {
4902 loge("Exception setting network preference default network", e);
4903 }
4904 }
4905 }
Junyu Lai35665cc2022-12-19 17:37:48 +08004906
Junyu Lai00d92df2022-07-05 11:01:52 +08004907 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004908 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004909 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004910
4911 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004912 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004913 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004914 }
4915 }
4916
Chalard Jean0354d8c2021-01-12 10:58:56 +09004917 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4918 // needed for this offer.
4919 for (final NetworkOfferInfo noi : mNetworkOffers) {
4920 for (final NetworkRequest req : nri.mRequests) {
4921 if (req.isRequest() && noi.offer.neededFor(req)) {
4922 noi.offer.onNetworkUnneeded(req);
4923 }
4924 }
4925 }
James Mattisa076c532020-12-02 14:12:41 -08004926 }
4927
James Mattis3ce3d3c2021-02-09 18:18:28 -08004928 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4929 for (final NetworkRequestInfo nri : nris) {
4930 if (mDefaultRequest == nri) {
4931 // Make sure we never remove the default request.
4932 continue;
4933 }
4934 handleRemoveNetworkRequest(nri);
4935 }
4936 }
4937
James Mattisa076c532020-12-02 14:12:41 -08004938 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4939 // listens don't have a singular affected Network. Check all networks to see
4940 // if this listen request applies and remove it.
4941 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4942 nai.removeRequest(req.requestId);
4943 if (req.networkCapabilities.hasSignalStrength()
4944 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4945 updateSignalStrengthThresholds(nai, "RELEASE", req);
4946 }
4947 }
4948 }
4949
4950 /**
4951 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4952 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4953 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4954 */
4955 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4956 boolean wasKept = false;
4957 final NetworkAgentInfo nai = nri.getSatisfier();
4958 if (nai != null) {
4959 final int requestLegacyType = nri.getActiveRequest().legacyType;
4960 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4961 nai.removeRequest(nri.getActiveRequest().requestId);
4962 if (VDBG || DDBG) {
4963 log(" Removing from current network " + nai.toShortString()
4964 + ", leaving " + nai.numNetworkRequests() + " requests.");
4965 }
4966 // If there are still lingered requests on this network, don't tear it down,
4967 // but resume lingering instead.
4968 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004969 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004970 notifyNetworkLosing(nai, now);
4971 }
4972 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4973 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4974 teardownUnneededNetwork(nai);
4975 } else {
4976 wasKept = true;
4977 }
James Mattisa076c532020-12-02 14:12:41 -08004978 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4979 // Went from foreground to background.
4980 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004981 }
4982
Erik Kline0c04b742016-07-07 16:50:58 +09004983 // Maintain the illusion. When this request arrived, we might have pretended
4984 // that a network connected to serve it, even though the network was already
4985 // connected. Now that this request has gone away, we might have to pretend
4986 // that the network disconnected. LegacyTypeTracker will generate that
4987 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004988 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004989 boolean doRemove = true;
4990 if (wasKept) {
4991 // check if any of the remaining requests for this network are for the
4992 // same legacy type - if so, don't remove the nai
4993 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4994 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004995 if (otherRequest.legacyType == requestLegacyType
4996 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004997 if (DBG) log(" still have other legacy request - leaving");
4998 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004999 }
5000 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005001 }
5002
Erik Kline0c04b742016-07-07 16:50:58 +09005003 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005004 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005005 }
5006 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005007 }
5008 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005009
Junyu Lai00d92df2022-07-05 11:01:52 +08005010 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005011 return checkAnyPermissionOf(
5012 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5013 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5014 }
5015
Lorenzo Colittid6459092016-07-04 12:55:44 +09005016 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005017 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005018 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005019 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005020 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005021 }
5022
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005023 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005024 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5025 enforceNetworkStackSettingsOrSetup();
5026 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5027 encodeBool(accept), encodeBool(always), network));
5028 }
5029
5030 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005031 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005032 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005033 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5034 }
5035
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005036 @Override
5037 public void setTestAllowBadWifiUntil(long timeMs) {
5038 enforceSettingsPermission();
5039 if (!Build.isDebuggable()) {
5040 throw new IllegalStateException("Does not support in non-debuggable build");
5041 }
5042
5043 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5044 throw new IllegalArgumentException("It should not exceed "
5045 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5046 }
5047
5048 mHandler.sendMessage(
5049 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5050 }
5051
chiachangwange0192a72023-02-06 13:25:01 +00005052 @Override
5053 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5054 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005055
5056 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5057 throw new IllegalArgumentException("Argument should not exceed "
5058 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5059 }
5060
5061 mHandler.sendMessage(
5062 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5063 }
5064
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005065 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5066 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5067 " accept=" + accept + " always=" + always);
5068
5069 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5070 if (nai == null) {
5071 // Nothing to do.
5072 return;
5073 }
5074
Chalard Jean254bd162022-08-25 13:04:51 +09005075 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005076 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005077 return;
5078 }
5079
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005080 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005081 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005082 }
5083
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005084 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5085 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005086 // If network becomes partial connectivity and user already accepted to use this
5087 // network, we should respect the user's option and don't need to popup the
5088 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005089 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005090 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005091 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005092 }
5093
5094 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005095 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005096 }
5097
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005098 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005099 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005100 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005101 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005102 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005103 }
5104
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005105 }
5106
lucaslin2240ef62019-03-12 13:08:03 +08005107 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5108 boolean always) {
5109 if (DBG) {
5110 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5111 + " always=" + always);
5112 }
5113
5114 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5115 if (nai == null) {
5116 // Nothing to do.
5117 return;
5118 }
5119
Chalard Jean254bd162022-08-25 13:04:51 +09005120 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005121 // The network validated while the dialog box was up. Take no action.
5122 return;
5123 }
5124
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005125 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5126 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005127 }
5128
5129 // TODO: Use the current design or save the user choice into IpMemoryStore.
5130 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005131 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005132 }
5133
5134 if (!accept) {
5135 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005136 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005137 // Tear down the network.
5138 teardownUnneededNetwork(nai);
5139 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005140 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5141 // result in a partial connectivity result which will be processed by
5142 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005143 //
5144 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5145 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005146 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005147 }
5148 }
5149
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005150 private void handleSetAvoidUnvalidated(Network network) {
5151 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005152 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005153 // Nothing to do. The network either disconnected or revalidated.
5154 return;
5155 }
Chalard Jean254bd162022-08-25 13:04:51 +09005156 if (0L == nai.getAvoidUnvalidated()) {
5157 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005158 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005159 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005160 }
5161 }
5162
Chalard Jean5fb43c72022-09-08 19:03:14 +09005163 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005164 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005165 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005166 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09005167 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005168 }
5169
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005170 @Override
5171 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005172 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005173 mHandler.post(() -> {
5174 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5175 if (nai == null) return;
5176 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005177 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005178 });
5179 }
5180
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005181 /**
5182 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5183 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005184 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005185 * @param appExtras Bundle to use as intent extras for the captive portal application.
5186 * Must be treated as opaque to avoid preventing the captive portal app to
5187 * update its arguments.
5188 */
5189 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005190 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005191 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5192 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005193
5194 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5195 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005196 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5197 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005198 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5199
lucaslin75ff7022020-12-17 04:14:35 +08005200 final long token = Binder.clearCallingIdentity();
5201 try {
5202 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5203 } finally {
5204 Binder.restoreCallingIdentity(token);
5205 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005206 }
5207
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005208 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5209 private final Network mNetwork;
5210
5211 private CaptivePortalImpl(Network network) {
5212 mNetwork = network;
5213 }
5214
5215 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005216 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005217 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5218 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005219 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5220 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5221 // Since the network will be disconnected, skip notifying NetworkMonitor
5222 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005223 }
5224
Chiachang Wang938bfba2020-01-09 13:50:55 +08005225 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005226 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005227 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005228 }
5229
5230 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005231 public void appRequest(final int request) {
5232 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5233 if (nm == null) return;
5234
5235 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005236 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005237 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005238 }
5239 }
5240
5241 @Nullable
5242 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5243 // getNetworkAgentInfoForNetwork is thread-safe
5244 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5245 if (nai == null) return null;
5246
5247 // nai.networkMonitor() is thread-safe
5248 return nai.networkMonitor();
5249 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005250 }
5251
Hugo Benichic9048bc2016-09-14 23:23:08 +00005252 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005253 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005254 }
5255
Chalard Jean020b93a2022-09-01 13:20:14 +09005256 private boolean activelyPreferBadWifi() {
5257 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5258 }
5259
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005260 /**
5261 * Return whether the device should maintain continuous, working connectivity by switching away
5262 * from WiFi networks having no connectivity.
5263 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5264 */
5265 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005266 if (!checkNetworkStackPermission()) {
5267 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5268 }
5269 return avoidBadWifi();
5270 }
5271
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005272 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005273 ensureRunningOnConnectivityServiceThread();
5274 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005275 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005276 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005277 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005278 if (avoidBadWifi) {
5279 // If the device is now avoiding bad wifi, remove notifications that might have
5280 // been put up when the device didn't.
5281 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5282 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005283 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005284 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5285 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5286 for (final NetworkOfferInfo noi : offersToUpdate) {
5287 updateOfferScore(noi.offer);
5288 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005289 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005290 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005291 }
5292
Erik Kline95ecfee2016-10-02 18:02:14 +09005293 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005294 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005295 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005296 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005297 if (!configRestrict) {
5298 pw.println("Bad Wi-Fi avoidance: unrestricted");
5299 return;
5300 }
5301
5302 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5303 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005304 pw.println("Config restrict: " + configRestrict);
5305 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005306
Chalard Jeane0fdea32022-09-14 21:44:22 +09005307 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005308 String description;
5309 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005310 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005311 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005312 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005313 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005314 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005315 description = "avoid";
5316 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005317 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005318 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005319 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005320
5321 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5322 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005323 if (null == configValue) {
5324 description = "unset";
5325 } else if (configValue) {
5326 description = "force true";
5327 } else {
5328 description = "force false";
5329 }
5330 pw.println("Actively prefer bad wifi conf: " + description);
5331 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005332 pw.println("Network overrides:");
5333 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005334 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005335 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005336 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005337 }
5338 }
5339 pw.decreaseIndent();
5340 pw.decreaseIndent();
5341 }
5342
paulhu7746e4e2020-06-09 19:07:03 +08005343 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5344 // unify the method.
5345 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5346 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5347 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5348 return settingsComponent != null
5349 ? settingsComponent.getPackageName() : "com.android.settings";
5350 }
5351
lucaslinb1e8e382019-01-24 15:55:30 +08005352 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005353 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005354 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005355 switch (type) {
5356 case NO_INTERNET:
5357 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005358 // High priority because it is only displayed for explicitly selected networks.
5359 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005360 break;
lucasline117e2e2019-10-22 18:27:33 +08005361 case PRIVATE_DNS_BROKEN:
5362 action = Settings.ACTION_WIRELESS_SETTINGS;
5363 // High priority because we should let user know why there is no internet.
5364 highPriority = true;
5365 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005366 case LOST_INTERNET:
5367 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005368 // High priority because it could help the user avoid unexpected data usage.
5369 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005370 break;
lucaslin2240ef62019-03-12 13:08:03 +08005371 case PARTIAL_CONNECTIVITY:
5372 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005373 // Don't bother the user with a high-priority notification if the network was not
5374 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005375 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005376 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005377 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005378 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005379 return;
5380 }
5381
5382 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005383 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005384 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005385 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005386 // Some OEMs have their own Settings package. Thus, need to get the current using
5387 // Settings package name instead of just use default name "com.android.settings".
5388 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5389 intent.setClassName(settingsPkgName,
5390 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005391 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005392
paulhu2af50222020-10-11 22:52:27 +08005393 PendingIntent pendingIntent = PendingIntent.getActivity(
5394 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005395 0 /* requestCode */,
5396 intent,
paulhu2af50222020-10-11 22:52:27 +08005397 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005398
Serik Beketayevec8ad212020-12-07 22:43:07 -08005399 mNotifier.showNotification(
5400 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005401 }
5402
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005403 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5404 // Don't prompt if the network is validated, and don't prompt on captive portals
5405 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005406 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005407 return false;
5408 }
5409
5410 // If a network has partial connectivity, always prompt unless the user has already accepted
5411 // partial connectivity and selected don't ask again. This ensures that if the device
5412 // automatically connects to a network that has partial Internet access, the user will
5413 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005414 // because we have prompted them.
5415 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005416 return true;
5417 }
5418
5419 // If a network has no Internet access, only prompt if the network was explicitly selected
5420 // and if the user has not already told us to use the network regardless of whether it
5421 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005422 if (nai.networkAgentConfig.explicitlySelected
5423 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005424 return true;
5425 }
5426
5427 return false;
5428 }
5429
Chalard Jean5fb43c72022-09-08 19:03:14 +09005430 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5431 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005432
Chalard Jean5fb43c72022-09-08 19:03:14 +09005433 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5434 if (null == nai) return;
5435
5436 if (nai.setEvaluated()) {
5437 // If setEvaluated() returned true, the network never had any form of connectivity.
5438 // This may have an impact on request matching if bad WiFi avoidance is off and the
5439 // network was found not to have Internet access.
5440 nai.updateScoreForNetworkAgentUpdate();
5441 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005442
5443 // Also, if this is WiFi and it should be preferred actively, now is the time to
5444 // prompt the user that they walked past and connected to a bad WiFi.
5445 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5446 && !avoidBadWifi()
5447 && activelyPreferBadWifi()) {
5448 // The notification will be removed if the network validates or disconnects.
5449 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5450 return;
5451 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005452 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005453
Chalard Jean5fb43c72022-09-08 19:03:14 +09005454 if (!shouldPromptUnvalidated(nai)) return;
5455
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005456 // Stop automatically reconnecting to this network in the future. Automatically connecting
5457 // to a network that provides no or limited connectivity is not useful, because the user
5458 // cannot use that network except through the notification shown by this method, and the
5459 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005460 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005461
Chalard Jean254bd162022-08-25 13:04:51 +09005462 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005463 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005464 } else {
5465 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5466 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005467 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005468
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005469 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5470 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005471 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005472
lucaslin2240ef62019-03-12 13:08:03 +08005473 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5474 return;
5475 }
5476
5477 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005478 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005479 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005480 }
5481
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005482 @Override
5483 public int getMultipathPreference(Network network) {
5484 enforceAccessPermission();
5485
5486 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005487 if (nai != null && nai.networkCapabilities
5488 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005489 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5490 }
5491
Aaron Huang9a57acf2020-12-08 10:03:29 +08005492 final NetworkPolicyManager netPolicyManager =
5493 mContext.getSystemService(NetworkPolicyManager.class);
5494
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005495 final long token = Binder.clearCallingIdentity();
5496 final int networkPreference;
5497 try {
5498 networkPreference = netPolicyManager.getMultipathPreference(network);
5499 } finally {
5500 Binder.restoreCallingIdentity(token);
5501 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005502 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005503 return networkPreference;
5504 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005505 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5506 }
5507
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005508 @Override
5509 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005510 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005511 }
5512
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005513 private class InternalHandler extends Handler {
5514 public InternalHandler(Looper looper) {
5515 super(looper);
5516 }
5517
5518 @Override
5519 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005520 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005521 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005522 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005523 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005524 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005525 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005526 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005527 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005528 break;
5529 }
Jason Monka69f1b02013-10-10 14:02:51 -04005530 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005531 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5532 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005533 break;
5534 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005535 case EVENT_REGISTER_NETWORK_PROVIDER: {
5536 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005537 break;
5538 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005539 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5540 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005541 break;
5542 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005543 case EVENT_REGISTER_NETWORK_OFFER: {
5544 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5545 break;
5546 }
5547 case EVENT_UNREGISTER_NETWORK_OFFER: {
5548 final NetworkOfferInfo offer =
5549 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5550 if (null != offer) {
5551 handleUnregisterNetworkOffer(offer);
5552 }
5553 break;
5554 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005555 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005556 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5557 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5558 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005559 break;
5560 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005561 case EVENT_REGISTER_NETWORK_REQUEST:
5562 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005563 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005564 break;
5565 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005566 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5567 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005568 handleRegisterNetworkRequestWithIntent(msg);
5569 break;
5570 }
Erik Kline155a59a2015-11-25 12:49:38 +09005571 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5572 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5573 handleTimedOutNetworkRequest(nri);
5574 break;
5575 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005576 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5577 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5578 break;
5579 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005580 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005581 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5582 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005583 break;
5584 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005585 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005586 Network network = (Network) msg.obj;
5587 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005588 break;
5589 }
lucaslin2240ef62019-03-12 13:08:03 +08005590 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5591 Network network = (Network) msg.obj;
5592 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5593 toBool(msg.arg2));
5594 break;
5595 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005596 case EVENT_SET_AVOID_UNVALIDATED: {
5597 handleSetAvoidUnvalidated((Network) msg.obj);
5598 break;
5599 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005600 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5601 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005602 break;
5603 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005604 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5605 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005606 break;
5607 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005608 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005609 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005610 mKeepaliveTracker.handleStartKeepalive(msg);
5611 break;
5612 }
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005613 case NetworkAgent.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09005614 final AutomaticOnOffKeepalive ki =
5615 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
5616 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005617
chiachangwang676c84e2023-02-14 09:22:05 +00005618 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005619 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005620 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00005621 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005622 for (NetworkAgentInfo n : mNetworkAgentInfos) {
5623 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00005624 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
5625 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005626 }
5627 }
5628
5629 // If the network no longer exists, then the keepalive should have been
5630 // cleaned up already. There is no point trying to resume keepalives.
5631 if (!networkFound) return;
5632
chiachangwang676c84e2023-02-14 09:22:05 +00005633 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005634 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00005635 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005636 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00005637 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005638 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005639 }
5640 break;
5641 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005642 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005643 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005644 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
5645 (IBinder) msg.obj);
5646 if (ki == null) {
5647 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00005648 return;
5649 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005650 final int reason = msg.arg2;
5651 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005652 break;
5653 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005654 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5655 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5656 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005657 break;
5658 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005659 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5660 handlePrivateDnsSettingsChanged();
5661 break;
dalyk1720e542018-03-05 12:42:22 -05005662 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5663 handlePrivateDnsValidationUpdate(
5664 (PrivateDnsValidationUpdate) msg.obj);
5665 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005666 case EVENT_UID_BLOCKED_REASON_CHANGED:
5667 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005668 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005669 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5670 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5671 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005672 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005673 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5674 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005675 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005676 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005677 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005678 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005679 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5680 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005681 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005682 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005683 }
lucaslin1193a5d2021-01-21 02:04:15 +08005684 case EVENT_REPORT_NETWORK_ACTIVITY:
5685 mNetworkActivityTracker.handleReportNetworkActivity();
5686 break;
paulhu51f77dc2021-06-07 02:34:20 +00005687 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5688 handleMobileDataPreferredUidsChanged();
5689 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005690 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5691 final long timeMs = ((Long) msg.obj).longValue();
5692 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5693 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005694 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5695 handleIngressRateLimitChanged();
5696 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005697 case EVENT_USER_DOES_NOT_WANT:
5698 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5699 if (nai == null) break;
5700 nai.onPreventAutomaticReconnect();
5701 nai.disconnect();
5702 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00005703 case EVENT_SET_VPN_NETWORK_PREFERENCE:
5704 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
5705 break;
chiachangwange0192a72023-02-06 13:25:01 +00005706 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
5707 final long time = ((Long) msg.obj).longValue();
5708 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
5709 break;
5710 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005711 }
5712 }
5713 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005714
Lorenzo Colittid6459092016-07-04 12:55:44 +09005715 @Override
markchien5776f962019-12-16 20:15:20 +08005716 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005717 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005718 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005719 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5720 Context.TETHERING_SERVICE);
5721 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005722 }
5723
Lorenzo Colittid6459092016-07-04 12:55:44 +09005724 @Override
markchien5776f962019-12-16 20:15:20 +08005725 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005726 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005727 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005728 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5729 Context.TETHERING_SERVICE);
5730 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005731 }
5732
Lorenzo Colittid6459092016-07-04 12:55:44 +09005733 @Override
markchien5776f962019-12-16 20:15:20 +08005734 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005735 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005736 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005737 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5738 Context.TETHERING_SERVICE);
5739 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005740 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005741
markchien5776f962019-12-16 20:15:20 +08005742
Lorenzo Colittid6459092016-07-04 12:55:44 +09005743 @Override
markchien5776f962019-12-16 20:15:20 +08005744 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005745 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005746 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005747 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5748 Context.TETHERING_SERVICE);
5749
5750 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005751 }
5752
Lorenzo Colittid6459092016-07-04 12:55:44 +09005753 @Override
markchien5776f962019-12-16 20:15:20 +08005754 @Deprecated
5755 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005756 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005757 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5758 Context.TETHERING_SERVICE);
5759
5760 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005761 }
5762
Udam Saini8f7d6a72017-06-07 12:06:28 -07005763 @Override
markchien5776f962019-12-16 20:15:20 +08005764 @Deprecated
5765 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005766 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005767 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5768 Context.TETHERING_SERVICE);
5769 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005770 }
5771
Robert Greenwalte0b00512014-07-02 09:59:16 -07005772 // Called when we lose the default network and have no replacement yet.
5773 // This will automatically be cleared after X seconds or a new default network
5774 // becomes CONNECTED, whichever happens first. The timer is started by the
5775 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005776 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005777 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005778 if (mNetTransitionWakeLock.isHeld()) {
5779 return;
5780 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005781 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005782 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5783 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005784 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005785 mWakelockLogs.log("ACQUIRE for " + forWhom);
5786 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005787 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005788 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005789 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005790 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005791
Hugo Benichi471b62a2017-03-30 23:18:10 +09005792 // Called when we gain a new default network to release the network transition wakelock in a
5793 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5794 // message is cancelled.
5795 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005796 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005797 if (!mNetTransitionWakeLock.isHeld()) {
5798 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005799 }
5800 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005801 // Cancel self timeout on wakelock hold.
5802 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5803 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5804 mHandler.sendMessageDelayed(msg, 1000);
5805 }
5806
5807 // Called when either message of ensureNetworkTransitionWakelock or
5808 // scheduleReleaseNetworkTransitionWakelock is processed.
5809 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5810 String event = eventName(eventId);
5811 synchronized (this) {
5812 if (!mNetTransitionWakeLock.isHeld()) {
5813 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005814 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005815 return;
5816 }
5817 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005818 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5819 mTotalWakelockDurationMs += lockDuration;
5820 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5821 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005822 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005823 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005824 }
5825
Robert Greenwalt986c7412010-09-08 15:24:47 -07005826 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005827 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005828 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005829 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005830 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005831 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005832 }
5833
Lorenzo Colittid6459092016-07-04 12:55:44 +09005834 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005835 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005836 enforceAccessPermission();
5837 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005838 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005839 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005840
5841 final NetworkAgentInfo nai;
5842 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005843 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005844 } else {
5845 nai = getNetworkAgentInfoForNetwork(network);
5846 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005847
5848 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005849 mHandler.obtainMessage(
5850 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005851 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005852
Hugo Benichid6b510a2017-04-06 17:22:18 +09005853 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005854 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005855 if (nai == null
5856 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005857 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005858 return;
5859 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005860 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005861 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005862 mConnectivityDiagnosticsHandler.sendMessage(
5863 mConnectivityDiagnosticsHandler.obtainMessage(
5864 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5865 new ReportedNetworkConnectivityInfo(
5866 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005867 return;
5868 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005869 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005870 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005871 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005872 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005873 // Validating a network that has not yet connected could result in a call to
5874 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005875 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005876 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005877 }
paulhu7aeba372020-12-30 00:42:19 +08005878 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5879 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005880 return;
5881 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005882
5883 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5884 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5885 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5886 // completed.
5887 mConnectivityDiagnosticsHandler.sendMessage(
5888 mConnectivityDiagnosticsHandler.obtainMessage(
5889 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5890 new ReportedNetworkConnectivityInfo(
5891 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005892 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005893 }
5894
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005895 // TODO: call into netd.
5896 private boolean queryUserAccess(int uid, Network network) {
5897 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5898 if (nai == null) return false;
5899
5900 // Any UID can use its default network.
5901 if (nai == getDefaultNetworkForUid(uid)) return true;
5902
5903 // Privileged apps can use any network.
5904 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5905 return true;
5906 }
5907
5908 // An unprivileged UID can use a VPN iff the VPN applies to it.
5909 if (nai.isVPN()) {
5910 return nai.networkCapabilities.appliesToUid(uid);
5911 }
5912
5913 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5914 // sockets, i.e., if it is the owner.
5915 final NetworkAgentInfo vpn = getVpnForUid(uid);
5916 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5917 && uid != vpn.networkCapabilities.getOwnerUid()) {
5918 return false;
5919 }
5920
5921 // The UID's permission must be at least sufficient for the network. Since the restricted
5922 // permission was already checked above, that just leaves background networks.
5923 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5924 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5925 }
5926
5927 // Unrestricted network. Anyone gets to use it.
5928 return true;
5929 }
5930
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005931 /**
5932 * Returns information about the proxy a certain network is using. If given a null network, it
5933 * it will return the proxy for the bound network for the caller app or the default proxy if
5934 * none.
5935 *
5936 * @param network the network we want to get the proxy information for.
5937 * @return Proxy information if a network has a proxy configured, or otherwise null.
5938 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005939 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005940 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005941 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005942 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005943 if (network == null) {
5944 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005945 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005946 true);
5947 if (activeNetwork == null) {
5948 return null;
5949 }
5950 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005951 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005952 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5953 // caller may not have.
5954 return getLinkPropertiesProxyInfo(network);
5955 }
5956 // No proxy info available if the calling UID does not have network access.
5957 return null;
5958 }
5959
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005960
5961 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005962 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5963 if (nai == null) return null;
5964 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005965 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5966 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005967 }
5968 }
5969
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005970 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005971 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005972 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005973 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005974 }
5975
Chalard Jean777e2e52018-06-07 18:02:37 +09005976 @Override
5977 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005978 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005979 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005980 }
5981
Junyu Lai970963e2022-10-25 15:46:47 +08005982 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005983 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005984 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005985 proxy = null;
5986 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005987 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005988 }
5989
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005990 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5991 // when any network changes proxy.
5992 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5993 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08005994 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
5995 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05005996 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5997
Chalard Jean7d97afc2018-06-07 17:41:29 +09005998 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005999 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006000 }
6001 }
6002
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006003 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006004 final private HashMap<Uri, Integer> mUriEventMap;
6005 final private Context mContext;
6006 final private Handler mHandler;
6007
6008 SettingsObserver(Context context, Handler handler) {
6009 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006010 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006011 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006012 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006013 }
6014
Erik Kline05f2b402015-04-30 12:58:40 +09006015 void observe(Uri uri, int what) {
6016 mUriEventMap.put(uri, what);
6017 final ContentResolver resolver = mContext.getContentResolver();
6018 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006019 }
6020
6021 @Override
6022 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006023 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006024 }
6025
6026 @Override
6027 public void onChange(boolean selfChange, Uri uri) {
6028 final Integer what = mUriEventMap.get(uri);
6029 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006030 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006031 } else {
6032 loge("No matching event to send for URI=" + uri);
6033 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006034 }
6035 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006036
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006037 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006038 Log.d(TAG, s);
6039 }
6040
6041 private static void logw(String s) {
6042 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006043 }
6044
Daniel Brightf9e945b2020-06-15 16:10:01 -07006045 private static void logwtf(String s) {
6046 Log.wtf(TAG, s);
6047 }
6048
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006049 private static void logwtf(String s, Throwable t) {
6050 Log.wtf(TAG, s, t);
6051 }
6052
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006053 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006054 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006055 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006056
Hugo Benichi39621362017-02-11 17:04:43 +09006057 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006058 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006059 }
6060
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006061 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006062 * Return the information of all ongoing VPNs.
6063 *
6064 * <p>This method is used to update NetworkStatsService.
6065 *
6066 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006067 */
junyulai2050bed2021-01-23 09:46:34 +08006068 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006069 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006070 if (mLockdownEnabled) {
6071 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006072 }
junyulai2050bed2021-01-23 09:46:34 +08006073 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006074 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006075 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006076 if (info != null) {
6077 infoList.add(info);
6078 }
6079 }
junyulai2050bed2021-01-23 09:46:34 +08006080 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006081 }
6082
6083 /**
6084 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006085 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006086 */
junyulai2050bed2021-01-23 09:46:34 +08006087 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006088 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006089 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6090 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006091 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6092 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6093 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006094 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6095 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006096 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006097 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006098 }
6099 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006100
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006101 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006102
6103 List<String> interfaces = new ArrayList<>();
6104 for (Network network : underlyingNetworks) {
6105 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6106 if (underlyingNai == null) continue;
6107 LinkProperties lp = underlyingNai.linkProperties;
6108 for (String iface : lp.getAllInterfaceNames()) {
6109 if (!TextUtils.isEmpty(iface)) {
6110 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006111 }
6112 }
Benedict Wong34857f82019-06-12 17:46:15 +00006113 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006114
6115 if (interfaces.isEmpty()) return null;
6116
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006117 // Must be non-null or NetworkStatsService will crash.
6118 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6119 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006120 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006121 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006122
junyulai2050bed2021-01-23 09:46:34 +08006123 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6124 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006125 }
6126
James Mattisd31bdfa2020-12-23 16:37:26 -08006127 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006128 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6129 Network[] underlyingNetworks) {
6130 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006131 if (underlyingNetworks == null && defaultNetwork != null) {
6132 // null underlying networks means to track the default.
6133 underlyingNetworks = new Network[] { defaultNetwork };
6134 }
6135 return underlyingNetworks;
6136 }
6137
6138 // Returns true iff |network| is an underlying network of |nai|.
6139 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6140 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6141 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006142 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006143 final Network[] underlying = underlyingNetworksOrDefault(
6144 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006145 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006146 }
6147
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006148 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006149 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006150 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006151 * When underlying networks change, such networks may have to update capabilities to reflect
6152 * things like the metered bit, their transports, and so on. The capabilities are calculated
6153 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006154 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006155 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006156 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006157 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006158 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006159 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006160 }
6161 }
6162 }
6163
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006164 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6165 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6166 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6167 // a VPN is not up.
6168 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6169 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6170 for (UidRange range : blockedUidRanges) {
6171 if (range.contains(uid)) return true;
6172 }
6173 return false;
6174 }
6175
6176 @Override
6177 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006178 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006179 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6180 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6181 }
6182
6183 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6184 if (DBG) {
6185 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6186 + Arrays.toString(ranges));
6187 }
6188 // Cannot use a Set since the list of UID ranges might contain duplicates.
6189 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6190 for (int i = 0; i < ranges.length; i++) {
6191 if (requireVpn) {
6192 newVpnBlockedUidRanges.add(ranges[i]);
6193 } else {
6194 newVpnBlockedUidRanges.remove(ranges[i]);
6195 }
6196 }
6197
6198 try {
6199 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6200 } catch (RemoteException | ServiceSpecificException e) {
6201 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6202 + Arrays.toString(ranges) + "): netd command failed: " + e);
6203 }
6204
Motomu Utsumib08654c2022-05-11 05:56:26 +00006205 if (SdkLevel.isAtLeastT()) {
6206 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6207 }
6208
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006209 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6210 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006211 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6212 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006213 }
6214
6215 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6216 }
6217
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006218 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006219 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006220 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006221 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006222 }
6223
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006224 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6225 return mLockdownEnabled
6226 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6227 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006228 }
6229
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006230 private NetworkAgentInfo getLegacyLockdownNai() {
6231 if (!mLockdownEnabled) {
6232 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006233 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006234 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006235 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6236 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006237
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006238 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006239 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6240 // a local variable. There is no need to make a copy because its contents cannot change.
6241 final Network[] underlying = nai.declaredUnderlyingNetworks;
6242 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006243 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006244 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006245
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006246 // The legacy lockdown VPN always uses the default network.
6247 // If the VPN's underlying network is no longer the current default network, it means that
6248 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006249 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6250 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006251 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006252 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006253 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006254 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006255
6256 return nai;
6257 };
6258
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006259 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6260 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6261 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006262 private DetailedState getLegacyLockdownState(DetailedState origState) {
6263 if (origState != DetailedState.CONNECTED) {
6264 return origState;
6265 }
6266 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6267 ? DetailedState.CONNECTING
6268 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006269 }
6270
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006271 private void filterForLegacyLockdown(NetworkInfo ni) {
6272 if (!mLockdownEnabled || !ni.isConnected()) return;
6273 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6274 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6275 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6276 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6277 // network, this time with a state of CONNECTED.
6278 //
6279 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6280 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6281 // is not too far off the truth, since an always-on VPN, when not connected, is always
6282 // trying to reconnect.
6283 if (getLegacyLockdownNai() == null) {
6284 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6285 }
6286 }
6287
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006288 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006289 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006290 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006291 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006292 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6293 return;
6294 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006295 final long ident = Binder.clearCallingIdentity();
6296 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006297 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006298 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006299 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006300 } finally {
6301 Binder.restoreCallingIdentity(ident);
6302 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006303 }
Wink Savillecb117d32013-08-29 14:57:08 -07006304
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006305 @Override
6306 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006307 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006308 final long ident = Binder.clearCallingIdentity();
6309 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006310 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006311 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006312 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6313 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006314 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006315 } finally {
6316 Binder.restoreCallingIdentity(ident);
6317 }
6318 }
6319
James Mattis02220e22021-03-13 19:27:21 -08006320 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006321 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6322 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6323 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006324 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006325 }
6326
James Mattis02220e22021-03-13 19:27:21 -08006327 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006328 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006329 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006330 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6331 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006332 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006333 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6334 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6335 }
junyulaid91e7052020-08-28 13:44:33 +08006336 }
6337
James Mattis02220e22021-03-13 19:27:21 -08006338 private void onPackageChanged(@NonNull final String packageName) {
6339 // This is necessary in case a package is added or removed, but also when it's replaced to
6340 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6341 // as one in the preferences, then it should follow the same routing as that other package,
6342 // which means updating the rules is never to be needed in this case (whether it joins or
6343 // leaves a UID with a preference).
6344 if (isMappedInOemNetworkPreference(packageName)) {
6345 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6346 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006347
6348 // Invalidates cache entry when the package is updated.
6349 synchronized (mSelfCertifiedCapabilityCache) {
6350 mSelfCertifiedCapabilityCache.remove(packageName);
6351 }
James Mattis02220e22021-03-13 19:27:21 -08006352 }
6353
6354 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006355 @Override
6356 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006357 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006358 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006359 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006360
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006361 // User should be filled for below intents, check the existence.
6362 if (user == null) {
6363 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6364 return;
6365 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006366
Lorenzo Colitticd675292021-02-04 17:32:07 +09006367 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006368 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006369 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006370 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006371 } else {
junyulaid91e7052020-08-28 13:44:33 +08006372 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006373 }
6374 }
6375 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006376
James Mattis02220e22021-03-13 19:27:21 -08006377 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6378 @Override
6379 public void onReceive(Context context, Intent intent) {
6380 ensureRunningOnConnectivityServiceThread();
6381 switch (intent.getAction()) {
6382 case Intent.ACTION_PACKAGE_ADDED:
6383 case Intent.ACTION_PACKAGE_REMOVED:
6384 case Intent.ACTION_PACKAGE_REPLACED:
6385 onPackageChanged(intent.getData().getSchemeSpecificPart());
6386 break;
6387 default:
6388 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6389 }
6390 }
6391 };
6392
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006393 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006394 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006395
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006396 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006397 public final String name;
6398 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006399 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006400 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006401
lifraf3a3492021-03-10 13:58:14 +08006402 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6403 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006404 this.name = name;
6405 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006406 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006407 mDeathRecipient = deathRecipient;
6408
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006409 if (mDeathRecipient == null) {
6410 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006411 }
6412 }
6413
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006414 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006415 try {
6416 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6417 } catch (RemoteException e) {
6418 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006419 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006420 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006421 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006422
James Mattis4fce5d12020-11-12 15:53:42 -08006423 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6424 for (int i = 0; i < requests.size(); i++) {
6425 ensureNetworkRequestHasType(requests.get(i));
6426 }
6427 }
6428
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006429 private void ensureNetworkRequestHasType(NetworkRequest request) {
6430 if (request.type == NetworkRequest.Type.NONE) {
6431 throw new IllegalArgumentException(
6432 "All NetworkRequests in ConnectivityService must have a type");
6433 }
6434 }
6435
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006436 /**
6437 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006438 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006439 */
James Mattis258ea3c2020-11-15 15:04:40 -08006440 @VisibleForTesting
6441 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006442 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6443 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006444 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006445
James Mattisa076c532020-12-02 14:12:41 -08006446 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6447 void setSatisfier(
6448 @Nullable final NetworkAgentInfo satisfier,
6449 @Nullable final NetworkRequest activeRequest) {
6450 mSatisfier = satisfier;
6451 mActiveRequest = activeRequest;
6452 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006453
James Mattisd31bdfa2020-12-23 16:37:26 -08006454 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006455 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006456 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006457 private NetworkAgentInfo mSatisfier;
6458 NetworkAgentInfo getSatisfier() {
6459 return mSatisfier;
6460 }
6461
6462 // The request in mRequests assigned to a network agent. This is null if none of the
6463 // requests in mRequests can be satisfied. This member has the constraint of only being
6464 // accessible on the handler thread.
6465 @Nullable
6466 private NetworkRequest mActiveRequest;
6467 NetworkRequest getActiveRequest() {
6468 return mActiveRequest;
6469 }
6470
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006471 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006472 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006473 @Nullable
6474 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006475
6476 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006477 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006478 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006479 final int mPid;
6480 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006481 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006482 @Nullable
6483 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006484
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006485 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006486 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006487
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006488 // Effective UID of this request. This is different from mUid when a privileged process
6489 // files a request on behalf of another UID. This UID is used to determine blocked status,
6490 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6491 // maximum limit of registered callbacks per UID.
6492 final int mAsUid;
6493
paulhu48291862021-07-14 14:53:57 +08006494 // Preference order of this request.
6495 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006496
James Mattis3ce3d3c2021-02-09 18:18:28 -08006497 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6498 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6499 // maintained for keying off of. This is only a concern when the original nri
6500 // mNetworkRequests changes which happens currently for apps that register callbacks to
6501 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6502 // that match the per-app default nri that currently tracks the calling app's uid so that
6503 // callbacks are fired at the appropriate time. When the callbacks fire,
6504 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6505 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6506 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6507 @NonNull
6508 private final NetworkRequest mNetworkRequestForCallback;
6509 NetworkRequest getNetworkRequestForCallback() {
6510 return mNetworkRequestForCallback;
6511 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006512
James Mattisd31bdfa2020-12-23 16:37:26 -08006513 /**
6514 * Get the list of UIDs this nri applies to.
6515 */
6516 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006517 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006518 // networkCapabilities.getUids() returns a defensive copy.
6519 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006520 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6521 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006522 }
6523
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006524 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6525 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006526 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006527 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006528 }
6529
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006530 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006531 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006532 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006533 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006534 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006535 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006536 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006537 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006538 mBinder = null;
6539 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006540 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006541 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006542 mPerUidCounter = getRequestCounter(this);
6543 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006544 /**
6545 * Location sensitive data not included in pending intent. Only included in
6546 * {@link NetworkCallback}.
6547 */
6548 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006549 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006550 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006551 }
6552
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006553 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006554 @Nullable final IBinder binder,
6555 @NetworkCallback.Flag int callbackFlags,
6556 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006557 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6558 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006559 }
6560
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006561 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006562 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006563 @Nullable final IBinder binder,
6564 @NetworkCallback.Flag int callbackFlags,
6565 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006566 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006567 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006568 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006569 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006570 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006571 mBinder = binder;
6572 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006573 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006574 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006575 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006576 mPerUidCounter = getRequestCounter(this);
6577 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006578 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006579 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006580 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006581 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006582 }
6583
James Mattis3ce3d3c2021-02-09 18:18:28 -08006584 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6585 @NonNull final List<NetworkRequest> r) {
6586 super();
6587 ensureAllNetworkRequestsHaveType(r);
6588 mRequests = initializeRequests(r);
6589 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006590 final NetworkAgentInfo satisfier = nri.getSatisfier();
6591 if (null != satisfier) {
6592 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6593 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006594 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006595 // As this code creates a new NRI with a new set of requests, figure out which of
6596 // the list of requests should be the active request. It is always the first
6597 // request of the list that can be satisfied by the satisfier since the order of
6598 // requests is a priority order.
6599 // Note even in the presence of a satisfier there may not be an active request,
6600 // when the satisfier is the no-service network.
6601 NetworkRequest activeRequest = null;
6602 for (final NetworkRequest candidate : r) {
6603 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6604 activeRequest = candidate;
6605 break;
6606 }
6607 }
6608 setSatisfier(satisfier, activeRequest);
6609 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006610 mMessenger = nri.mMessenger;
6611 mBinder = nri.mBinder;
6612 mPid = nri.mPid;
6613 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006614 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006615 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006616 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006617 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006618 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006619 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006620 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006621 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006622 }
6623
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006624 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006625 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006626 }
6627
paulhue9913722021-05-26 15:19:20 +08006628 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006629 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006630 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006631 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006632 }
6633
James Mattis2516da32021-01-31 17:06:19 -08006634 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6635 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6636 // false.
6637 boolean isBeingSatisfied() {
6638 return (null != mSatisfier && null != mActiveRequest);
6639 }
6640
James Mattis3d229892020-11-16 16:46:28 -08006641 boolean isMultilayerRequest() {
6642 return mRequests.size() > 1;
6643 }
6644
James Mattis45d81842021-01-10 14:24:24 -08006645 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6646 // Creating a defensive copy to prevent the sender from modifying the list being
6647 // reflected in the return value of this method.
6648 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006649 return Collections.unmodifiableList(tempRequests);
6650 }
6651
James Mattisb1392002021-03-31 13:57:52 -07006652 void linkDeathRecipient() {
6653 if (null != mBinder) {
6654 try {
6655 mBinder.linkToDeath(this, 0);
6656 } catch (RemoteException e) {
6657 binderDied();
6658 }
6659 }
6660 }
6661
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006662 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006663 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006664 try {
6665 mBinder.unlinkToDeath(this, 0);
6666 } catch (NoSuchElementException e) {
6667 // Temporary workaround for b/194394697 pending analysis of additional logs
6668 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6669 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006670 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006671 }
6672
paulhu48291862021-07-14 14:53:57 +08006673 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6674 // Compare two preference orders.
6675 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006676 }
6677
paulhu48291862021-07-14 14:53:57 +08006678 int getPreferenceOrderForNetd() {
6679 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6680 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6681 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006682 }
paulhu48291862021-07-14 14:53:57 +08006683 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006684 }
6685
James Mattis4fce5d12020-11-12 15:53:42 -08006686 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006687 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09006688 // As an immutable collection, mRequests cannot change by the time the
6689 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6690 // is acceptable. Use handleReleaseNetworkRequest and not directly
6691 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6692 // the app already unregistered the request.
6693 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6694 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006695 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006696
James Mattis4fce5d12020-11-12 15:53:42 -08006697 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006698 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006699 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6700 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006701 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006702 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006703 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006704 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006705 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006706 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006707 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006708 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006709 }
6710
Junyu Lai00d92df2022-07-05 11:01:52 +08006711 // Keep backward compatibility since the ServiceSpecificException is used by
6712 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6713 public static class RequestInfoPerUidCounter extends PerUidCounter {
6714 RequestInfoPerUidCounter(int maxCountPerUid) {
6715 super(maxCountPerUid);
6716 }
6717
6718 @Override
6719 public synchronized void incrementCountOrThrow(int uid) {
6720 try {
6721 super.incrementCountOrThrow(uid);
6722 } catch (IllegalStateException e) {
6723 throw new ServiceSpecificException(
6724 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6725 "Uid " + uid + " exceeded its allotted requests limit");
6726 }
6727 }
6728
6729 @Override
6730 public synchronized void decrementCountOrThrow(int uid) {
6731 throw new UnsupportedOperationException("Use decrementCount instead.");
6732 }
6733
6734 public synchronized void decrementCount(int uid) {
6735 try {
6736 super.decrementCountOrThrow(uid);
6737 } catch (IllegalStateException e) {
6738 logwtf("Exception when decrement per uid request count: ", e);
6739 }
6740 }
6741 }
6742
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006743 // This checks that the passed capabilities either do not request a
6744 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006745 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006746 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006747 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006748 throw new SecurityException("Insufficient permissions to request a specific SSID");
6749 }
paulhu1a407652019-03-22 16:35:06 +08006750
6751 if (nc.hasSignalStrength()
6752 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6753 throw new SecurityException(
6754 "Insufficient permissions to request a specific signal strength");
6755 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006756 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006757
junyulai2217bec2021-04-14 23:33:31 +08006758 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006759 enforceNetworkFactoryPermission();
6760 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006761 }
6762
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006763 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006764 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006765 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006766 // mNetworkRequests may contain the same value multiple times in case of
6767 // multilayer requests. It won't matter in this case because the thresholds
6768 // will then be the same and be deduplicated as they enter the `thresholds` set.
6769 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006770 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6771 for (final NetworkRequest req : nri.mRequests) {
6772 if (req.networkCapabilities.hasSignalStrength()
6773 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6774 thresholds.add(req.networkCapabilities.getSignalStrength());
6775 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006776 }
6777 }
6778 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006779 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006780 }
6781
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006782 private void updateSignalStrengthThresholds(
6783 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006784 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006785
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006786 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006787 String detail;
6788 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6789 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6790 } else {
6791 detail = reason;
6792 }
6793 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006794 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006795 }
6796
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006797 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006798 }
6799
Chalard Jeandd421992021-12-16 23:16:02 +09006800 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006801 if (nc == null) {
6802 return;
6803 }
6804 NetworkSpecifier ns = nc.getNetworkSpecifier();
6805 if (ns == null) {
6806 return;
6807 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006808 if (ns instanceof MatchAllNetworkSpecifier) {
6809 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6810 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006811 }
6812
Chalard Jeandd421992021-12-16 23:16:02 +09006813 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006814 ensureValidNetworkSpecifier(nc);
6815 if (nc.isPrivateDnsBroken()) {
6816 throw new IllegalArgumentException("Can't request broken private DNS");
6817 }
Chalard Jeande665262022-02-25 16:12:12 +09006818 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006819 throw new IllegalArgumentException("Can't request access UIDs");
6820 }
lucasline117e2e2019-10-22 18:27:33 +08006821 }
6822
Chalard Jeandd421992021-12-16 23:16:02 +09006823 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6824 ensureListenableCapabilities(nc);
6825 final String badCapability = nc.describeFirstNonRequestableCapability();
6826 if (badCapability != null) {
6827 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6828 }
6829 }
6830
Chiachang Wang3bc52762021-11-25 14:17:57 +08006831 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6832 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006833 private boolean isTargetSdkAtleast(int version, int callingUid,
6834 @NonNull String callingPackageName) {
6835 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006836 final PackageManager pm =
6837 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006838 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006839 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006840 if (callingVersion < version) return false;
6841 } catch (PackageManager.NameNotFoundException e) { }
6842 return true;
6843 }
6844
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006845 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006846 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006847 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006848 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006849 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006850 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006851 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6852 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006853 throw new SecurityException("Insufficient permissions to specify legacy type");
6854 }
markchienfac84a22020-03-18 21:16:15 +08006855 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006856 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006857 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006858 // Privileged callers can track the default network of another UID by passing in a UID.
6859 if (asUid != Process.INVALID_UID) {
6860 enforceSettingsPermission();
6861 } else {
6862 asUid = callingUid;
6863 }
junyulaiad010792021-01-11 16:53:38 +08006864 final NetworkRequest.Type reqType;
6865 try {
6866 reqType = NetworkRequest.Type.values()[reqTypeInt];
6867 } catch (ArrayIndexOutOfBoundsException e) {
6868 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6869 }
6870 switch (reqType) {
6871 case TRACK_DEFAULT:
6872 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006873 // is unused and will be replaced by ones appropriate for the UID (usually, the
6874 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006875 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006876 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006877 enforceAccessPermission();
6878 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006879 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00006880 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006881 networkCapabilities = new NetworkCapabilities(defaultNc);
6882 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006883 case BACKGROUND_REQUEST:
6884 enforceNetworkStackOrSettingsPermission();
6885 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006886 case REQUEST:
6887 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6888 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006889 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006890 // TODO: this is incorrect. We mark the request as metered or not depending on
6891 // the state of the app when the request is filed, but we never change the
6892 // request if the app changes network state. http://b/29964605
6893 enforceMeteredApnPolicy(networkCapabilities);
6894 break;
junyulai1b1c8742021-03-12 20:05:08 +08006895 case LISTEN_FOR_BEST:
6896 enforceAccessPermission();
6897 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6898 break;
junyulaiad010792021-01-11 16:53:38 +08006899 default:
6900 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006901 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006902 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006903 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006904 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006905
junyulai1b1c8742021-03-12 20:05:08 +08006906 // Enforce FOREGROUND if the caller does not have permission to use background network.
6907 if (reqType == LISTEN_FOR_BEST) {
6908 restrictBackgroundRequestForCaller(networkCapabilities);
6909 }
6910
6911 // Set the UID range for this request to the single UID of the requester, unless the
6912 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006913 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6914 // are no visible methods to set the UIDs, an app could use reflection to try and get
6915 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006916 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006917 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6918 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006919
Etan Cohen85000162017-02-05 10:42:27 -08006920 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006921 throw new IllegalArgumentException("Bad timeout specified");
6922 }
Etan Cohen9786d922015-11-18 10:56:15 -08006923
James Mattis3ce3d3c2021-02-09 18:18:28 -08006924 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006925 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006926 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006927 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006928 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006929 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006930
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006931 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6932 // copied from the default request above. (This is necessary to ensure, for example, that
6933 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6934 // changes don't alter request matching.
6935 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6936 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006937 throw new IllegalStateException(
6938 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006939 + networkCapabilities + " vs. " + defaultNc);
6940 }
6941
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006942 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006943 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006944 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006945 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006946 }
6947 return networkRequest;
6948 }
6949
James Mattis3ce3d3c2021-02-09 18:18:28 -08006950 /**
6951 * Return the nri to be used when registering a network request. Specifically, this is used with
6952 * requests registered to track the default request. If there is currently a per-app default
6953 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6954 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006955 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6956 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006957 * @param nr the network request for the nri.
6958 * @param msgr the messenger for the nri.
6959 * @param binder the binder for the nri.
6960 * @param callingAttributionTag the calling attribution tag for the nri.
6961 * @return the nri to register.
6962 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006963 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006964 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006965 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006966 @Nullable String callingAttributionTag) {
6967 final List<NetworkRequest> requests;
6968 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6969 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006970 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006971 } else {
6972 requests = Collections.singletonList(nr);
6973 }
Roshan Pius951c0032020-12-22 15:10:42 -08006974 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006975 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006976 }
6977
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006978 private boolean shouldCheckCapabilitiesDeclaration(
6979 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
6980 @NonNull final String callingPackageName) {
6981 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
6982 // Only run the check if the change is enabled.
6983 if (!mDeps.isChangeEnabled(
6984 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
6985 callingPackageName, user)) {
6986 return false;
6987 }
6988
6989 return networkCapabilities.hasCapability(
6990 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
6991 || networkCapabilities.hasCapability(
6992 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
6993 }
6994
6995 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
6996 @NonNull final NetworkCapabilities networkCapabilities) {
6997 // This check is added to fix the linter error for "current min is 30", which is not going
6998 // to happen because Connectivity service always run in S+.
6999 if (!SdkLevel.isAtLeastS()) {
7000 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7001 return;
7002 }
7003 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007004 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007005 try {
7006 synchronized (mSelfCertifiedCapabilityCache) {
7007 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7008 callerPackageName);
7009 if (applicationNetworkCapabilities == null) {
7010 final PackageManager packageManager = mContext.getPackageManager();
7011 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7012 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7013 callerPackageName
7014 );
7015 final XmlResourceParser parser = packageManager
7016 .getResourcesForApplication(callerPackageName)
7017 .getXml(networkSliceProperty.getResourceId());
7018 applicationNetworkCapabilities =
7019 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7020 mSelfCertifiedCapabilityCache.put(callerPackageName,
7021 applicationNetworkCapabilities);
7022 }
7023
7024 }
7025 } catch (PackageManager.NameNotFoundException ne) {
7026 throw new SecurityException(
7027 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7028 + " property");
7029 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7030 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007031 } finally {
7032 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007033 }
7034
7035 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7036 networkCapabilities);
7037 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007038 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007039 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007040 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7041 callingPackageName)) {
7042 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7043 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007044 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007045 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7046 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7047 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7048 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007049 }
junyulai96bd9fe2022-03-08 17:36:42 +08007050 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007051 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007052 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007053 }
7054 }
7055
fenglu3f357402015-03-20 11:29:56 -07007056 @Override
fenglub00f4882015-04-21 17:12:05 -07007057 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007058 enforceAccessPermission();
7059 NetworkAgentInfo nai = null;
7060 if (network == null) {
7061 return false;
7062 }
7063 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007064 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007065 }
7066 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007067 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007068 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007069 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007070 Integer uidReqs = mBandwidthRequests.get(uid);
7071 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007072 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007073 }
7074 mBandwidthRequests.put(uid, ++uidReqs);
7075 }
fenglu3f357402015-03-20 11:29:56 -07007076 return true;
7077 }
7078 return false;
7079 }
7080
Felipe Leme0a5ae422016-06-20 16:36:29 -07007081 private boolean isSystem(int uid) {
7082 return uid < Process.FIRST_APPLICATION_UID;
7083 }
fenglu3f357402015-03-20 11:29:56 -07007084
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007085 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007086 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007087 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007088 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007089 return;
7090 }
Hugo Benichi39621362017-02-11 17:04:43 +09007091 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7092 // Policy already enforced.
7093 return;
7094 }
paulhuaf50d7d2020-12-24 19:47:34 +08007095 final long ident = Binder.clearCallingIdentity();
7096 try {
7097 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7098 // If UID is restricted, don't allow them to bring up metered APNs.
7099 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7100 }
7101 } finally {
7102 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007103 }
7104 }
7105
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007106 @Override
7107 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007108 PendingIntent operation, @NonNull String callingPackageName,
7109 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007110 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007111 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007112 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007113 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007114 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007115 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007116 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007117 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007118 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007119 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7120 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007121
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007122 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007123 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007124 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7125 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007126 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007127 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7128 nri));
7129 return networkRequest;
7130 }
7131
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007132 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7133 mHandler.sendMessageDelayed(
7134 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007135 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007136 }
7137
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007138 @Override
7139 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007140 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007141 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007142 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007143 }
7144
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007145 // In order to implement the compatibility measure for pre-M apps that call
7146 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7147 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7148 // This ensures it has permission to do so.
7149 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7150 if (nc == null) {
7151 return false;
7152 }
7153 int[] transportTypes = nc.getTransportTypes();
7154 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7155 return false;
7156 }
7157 try {
7158 mContext.enforceCallingOrSelfPermission(
7159 android.Manifest.permission.ACCESS_WIFI_STATE,
7160 "ConnectivityService");
7161 } catch (SecurityException e) {
7162 return false;
7163 }
7164 return true;
7165 }
7166
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007167 @Override
7168 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007169 Messenger messenger, IBinder binder,
7170 @NetworkCallback.Flag int callbackFlags,
7171 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007172 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007173 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7174 enforceAccessPermission();
7175 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007176
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007177 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007178 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007179 Binder.getCallingPid(), callingUid, callingPackageName);
7180 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007181 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7182 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7183 // onLost and onAvailable callbacks when networks move in and out of the background.
7184 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7185 // can't request networks.
7186 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007187 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007188
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007189 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007190 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007191 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007192 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007193 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007194 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007195
7196 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7197 return networkRequest;
7198 }
7199
7200 @Override
7201 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007202 PendingIntent operation, @NonNull String callingPackageName,
7203 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007204 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007205 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007206 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7207 enforceAccessPermission();
7208 }
Chalard Jeandd421992021-12-16 23:16:02 +09007209 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007210 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007211 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007212 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007213 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007214
7215 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007216 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007217 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7218 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007219 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007220
WeiZhang1cc3f172021-06-03 19:02:04 -05007221 mHandler.sendMessage(mHandler.obtainMessage(
7222 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007223 }
7224
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007225 /** Returns the next Network provider ID. */
7226 public final int nextNetworkProviderId() {
7227 return mNextNetworkProviderId.getAndIncrement();
7228 }
7229
Erik Kline0c04b742016-07-07 16:50:58 +09007230 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007231 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007232 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007233 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007234 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007235 }
7236
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007237 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7238 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007239 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7240 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7241 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007242 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007243 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007244 return;
7245 }
7246
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007247 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7248 mNetworkProviderInfos.put(npi.messenger, npi);
7249 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007250 }
7251
7252 @Override
7253 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007254 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007255 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007256 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007257 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007258 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7259 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007260 }
7261
7262 @Override
7263 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007264 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007265 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007266 }
7267
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007268 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007269 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007270 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7271 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007272 Objects.requireNonNull(score);
7273 Objects.requireNonNull(caps);
7274 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007275 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007276 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007277 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7278 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007279 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7280 }
7281
Chalard Jeanbb902a52021-08-18 01:35:19 +09007282 private void updateOfferScore(final NetworkOffer offer) {
7283 final boolean yieldToBadWiFi =
7284 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7285 final NetworkOffer newOffer = new NetworkOffer(
7286 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7287 offer.caps, offer.callback, offer.providerId);
7288 if (offer.equals(newOffer)) return;
7289 handleRegisterNetworkOffer(newOffer);
7290 }
7291
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007292 @Override
7293 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007294 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007295 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7296 }
7297
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007298 private void handleUnregisterNetworkProvider(Messenger messenger) {
7299 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7300 if (npi == null) {
7301 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007302 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007303 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007304 // Unregister all the offers from this provider
7305 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7306 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007307 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007308 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7309 toRemove.add(noi);
7310 }
7311 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007312 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007313 handleUnregisterNetworkOffer(noi);
7314 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007315 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007316 }
7317
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007318 @Override
James Mattisf7027322020-12-13 16:28:14 -08007319 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007320 if (request.hasTransport(TRANSPORT_TEST)) {
7321 enforceNetworkFactoryOrTestNetworksPermission();
7322 } else {
7323 enforceNetworkFactoryPermission();
7324 }
James Mattisf7027322020-12-13 16:28:14 -08007325 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7326 if (nri != null) {
7327 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7328 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7329 mHandler.post(() -> handleReleaseNetworkRequest(
7330 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7331 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007332 }
7333
Paul Jensen1f567382015-02-13 14:18:39 -05007334 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7335 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007336 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007337 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007338 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007339 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007340 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007341
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007342 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007343 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007344 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007345
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007346 // UID ranges for users that are currently blocked by VPNs.
7347 // This array is accessed and iterated on multiple threads without holding locks, so its
7348 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7349 // (on the handler thread).
7350 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7351
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007352 // Must only be accessed on the handler thread
7353 @NonNull
7354 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7355
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007356 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007357 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007358
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007359 // Current OEM network preferences. This object must only be written to on the handler thread.
7360 // Since it is immutable and always non-null, other threads may read it if they only care
7361 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007362 @NonNull
7363 private OemNetworkPreferences mOemNetworkPreferences =
7364 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007365 // Current per-profile network preferences. This object follows the same threading rules as
7366 // the OEM network preferences above.
7367 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007368 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7369 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007370
lucaslin3ba7cc22022-12-19 02:35:33 +00007371 // Current VPN network preferences. This object follows the same threading rules as the OEM
7372 // network preferences above.
7373 @NonNull
7374 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7375 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7376
paulhu51f77dc2021-06-07 02:34:20 +00007377 // A set of UIDs that should use mobile data preferentially if available. This object follows
7378 // the same threading rules as the OEM network preferences above.
7379 @NonNull
7380 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7381
James Mattiscb1e0362021-04-06 17:07:42 -07007382 // OemNetworkPreferences activity String log entries.
7383 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7384 @NonNull
7385 private final LocalLog mOemNetworkPreferencesLogs =
7386 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7387
James Mattis02220e22021-03-13 19:27:21 -08007388 /**
7389 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7390 * @param packageName the package name to check existence of a mapping for.
7391 * @return true if a mapping exists, false otherwise
7392 */
7393 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7394 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7395 }
7396
James Mattise3ef1912020-12-20 11:09:58 -08007397 // The always-on request for an Internet-capable network that apps without a specific default
7398 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007399 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007400 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007401 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007402 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007403 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007404 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007405 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007406
James Mattisd31bdfa2020-12-23 16:37:26 -08007407 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7408 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7409 }
7410
7411 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007412 * Return the default network request currently tracking the given uid.
7413 * @param uid the uid to check.
7414 * @return the NetworkRequestInfo tracking the given uid.
7415 */
7416 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007417 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007418 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007419 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007420 // Checking the first request is sufficient as only multilayer requests will have more
7421 // than one request and for multilayer, all requests will track the same uids.
7422 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007423 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007424 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007425 highestPriorityNri = nri;
7426 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007427 }
7428 }
paulhuaa0743d2021-05-26 21:56:03 +08007429 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007430 }
7431
7432 /**
7433 * Get a copy of the network requests of the default request that is currently tracking the
7434 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007435 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7436 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007437 * @param requestorUid the uid to check the default for.
7438 * @param requestorPackageName the requestor's package name.
7439 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7440 */
7441 @NonNull
7442 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007443 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007444 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007445 getDefaultRequestTrackingUid(asUid).mRequests,
7446 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007447 }
7448
7449 /**
7450 * Copy the given nri's NetworkRequest collection.
7451 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007452 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7453 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007454 * @param requestorUid the uid to set on the copied collection.
7455 * @param requestorPackageName the package name to set on the copied collection.
7456 * @return the copied NetworkRequest collection.
7457 */
7458 @NonNull
7459 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007460 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7461 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007462 final List<NetworkRequest> requests = new ArrayList<>();
7463 for (final NetworkRequest nr : requestsToCopy) {
7464 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007465 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007466 nr.legacyType, nextNetworkRequestId(), nr.type));
7467 }
7468 return requests;
7469 }
7470
7471 @NonNull
7472 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007473 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7474 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007475 // These capabilities are for a TRACK_DEFAULT callback, so:
7476 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7477 // mDefaultRequest and a per-UID default request.
7478 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007479 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007480 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007481 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7482 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007483 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007484 restrictRequestUidsForCallerAndSetRequestorInfo(
7485 netCap, requestorUid, requestorPackageName);
7486 return netCap;
7487 }
7488
7489 /**
7490 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7491 * @param nr the network request to check for equality against.
7492 * @return the nri if one exists, null otherwise.
7493 */
7494 @Nullable
7495 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7496 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7497 if (nri.getNetworkRequestForCallback().equals(nr)) {
7498 return nri;
7499 }
7500 }
7501 return null;
7502 }
7503
7504 /**
7505 * Check if an nri is currently being managed by per-app default networking.
7506 * @param nri the nri to check.
7507 * @return true if this nri is currently being managed by per-app default networking.
7508 */
7509 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7510 // nri.mRequests.get(0) is only different from the original request filed in
7511 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7512 // functionality therefore if these two don't match, it means this particular nri is
7513 // currently being managed by a per-app default.
7514 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7515 }
7516
7517 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007518 * Determine if an nri is a managed default request that disallows default networking.
7519 * @param nri the request to evaluate
7520 * @return true if device-default networking is disallowed
7521 */
7522 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7523 // Check if this nri is a managed default that supports the default network at its
7524 // lowest priority request.
7525 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7526 final NetworkCapabilities lowestPriorityNetCap =
7527 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7528 return isPerAppDefaultRequest(nri)
7529 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7530 lowestPriorityNetCap));
7531 }
7532
Erik Kline05f2b402015-04-30 12:58:40 +09007533 // Request used to optionally keep mobile data active even when higher
7534 // priority networks like Wi-Fi are active.
7535 private final NetworkRequest mDefaultMobileDataRequest;
7536
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007537 // Request used to optionally keep wifi data active even when higher
7538 // priority networks like ethernet are active.
7539 private final NetworkRequest mDefaultWifiRequest;
7540
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007541 // Request used to optionally keep vehicle internal network always active
7542 private final NetworkRequest mDefaultVehicleRequest;
7543
James Mattisd31bdfa2020-12-23 16:37:26 -08007544 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7545 // network with no service. This NAI should never be matched against, nor should any public API
7546 // ever return the associated network. For this reason, this NAI is not in the list of available
7547 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7548 // default requests that don't support using the device default network which will ultimately
7549 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7550 @VisibleForTesting
7551 final NetworkAgentInfo mNoServiceNetwork;
7552
Chalard Jean5b409c72021-02-04 13:12:59 +09007553 // The NetworkAgentInfo currently satisfying the default request, if any.
7554 private NetworkAgentInfo getDefaultNetwork() {
7555 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007556 }
7557
James Mattis2516da32021-01-31 17:06:19 -08007558 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007559 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007560 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7561 // Currently, all network requests will have the same uids therefore checking the first
7562 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007563 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007564 if (null == uids) {
7565 continue;
7566 }
7567 for (final UidRange range : uids) {
7568 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007569 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007570 highestPriorityNri = nri;
7571 }
James Mattis2516da32021-01-31 17:06:19 -08007572 }
7573 }
7574 }
paulhuaa0743d2021-05-26 21:56:03 +08007575 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007576 }
7577
Varun Ananddf569952019-02-06 10:13:38 -08007578 @Nullable
7579 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7580 return nai != null ? nai.network : null;
7581 }
7582
7583 private void ensureRunningOnConnectivityServiceThread() {
7584 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7585 throw new IllegalStateException(
7586 "Not running on ConnectivityService thread: "
7587 + Thread.currentThread().getName());
7588 }
7589 }
7590
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007591 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007592 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7593 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007594 }
7595
Chalard Jean29d06db2018-05-02 21:14:54 +09007596 /**
7597 * Register a new agent with ConnectivityService to handle a network.
7598 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007599 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007600 * @param networkInfo the initial info associated with this network. It can be updated later :
7601 * see {@link #updateNetworkInfo}.
7602 * @param linkProperties the initial link properties of this network. They can be updated
7603 * later : see {@link #updateLinkProperties}.
7604 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007605 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007606 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007607 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007608 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007609 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007610 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007611 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007612 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007613 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7614 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007615 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7616 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7617 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007618 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007619 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007620 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007621 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007622 } else {
7623 enforceNetworkFactoryPermission();
7624 }
7625
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007626 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007627 final long token = Binder.clearCallingIdentity();
7628 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007629 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007630 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007631 } finally {
7632 Binder.restoreCallingIdentity(token);
7633 }
7634 }
7635
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007636 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007637 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007638 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7639 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007640
Chalard Jeandbc46952022-02-02 00:14:18 +09007641 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7642 // and mutate them at any time.
7643 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7644 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7645 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7646
Chalard Jean366c5252022-01-25 18:27:53 +09007647 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007648 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007649 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7650 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007651 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007652 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007653 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007654 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7655 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007656
Chalard Jeandbc46952022-02-02 00:14:18 +09007657 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007658 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007659 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007660 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007661 mDeps.getNetworkStack().makeNetworkMonitor(
7662 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007663 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7664 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007665 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007666 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007667 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007668 }
7669
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007670 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007671 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007672 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007673 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007674 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007675 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7676 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7677 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007678
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007679 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007680
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007681 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007682 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007683 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007684 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007685
7686 try {
7687 networkMonitor.start();
7688 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007689 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007690 }
Chalard Jean366c5252022-01-25 18:27:53 +09007691
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007692 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007693 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007694 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007695 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007696 }
7697
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007698 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7699 @NonNull public final NetworkOffer offer;
7700
7701 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7702 this.offer = offer;
7703 }
7704
7705 @Override
7706 public void binderDied() {
7707 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7708 }
7709 }
7710
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007711 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7712 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7713 if (npi.providerId == providerId) return true;
7714 }
7715 return false;
7716 }
7717
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007718 /**
7719 * Register or update a network offer.
7720 * @param newOffer The new offer. If the callback member is the same as an existing
7721 * offer, it is an update of that offer.
7722 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007723 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007724 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7725 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007726 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007727 // This may actually happen if a provider updates its score or registers and then
7728 // immediately unregisters. The offer would still be in the handler queue, but the
7729 // provider would have been removed.
7730 if (DBG) log("Received offer from an unregistered provider");
7731 return;
7732 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007733 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7734 if (null != existingOffer) {
7735 handleUnregisterNetworkOffer(existingOffer);
7736 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007737 if (DBG) {
7738 // handleUnregisterNetworkOffer has already logged the old offer
7739 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7740 }
7741 } else {
7742 if (DBG) {
7743 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7744 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007745 }
7746 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7747 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007748 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007749 } catch (RemoteException e) {
7750 noi.binderDied();
7751 return;
7752 }
7753 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007754 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007755 }
7756
7757 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7758 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007759 if (DBG) {
7760 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7761 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007762
7763 // If the provider removes the offer and dies immediately afterwards this
7764 // function may be called twice in a row, but the array will no longer contain
7765 // the offer.
7766 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007767 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007768 }
7769
7770 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7771 @NonNull final INetworkOfferCallback callback) {
7772 ensureRunningOnConnectivityServiceThread();
7773 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007774 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007775 }
7776 return null;
7777 }
7778
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007779 /**
7780 * Called when receiving LinkProperties directly from a NetworkAgent.
7781 * Stores into |nai| any data coming from the agent that might also be written to the network's
7782 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7783 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007784 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007785 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007786 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7787 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007788 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007789 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007790 }
7791
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007792 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007793 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007794 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007795
Lorenzo Colittid523d142020-04-01 20:16:30 +09007796 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7797 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7798 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007799 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007800
Suprabh Shukla1e312032023-01-24 03:36:37 -08007801 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007802
7803 // update filtering rules, need to happen after the interface update so netd knows about the
7804 // new interface (the interface name -> index map becomes initialized)
7805 updateVpnFiltering(newLp, oldLp, networkAgent);
7806
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007807 updateMtu(newLp, oldLp);
7808 // TODO - figure out what to do for clat
7809// for (LinkProperties lp : newLp.getStackedLinks()) {
7810// updateMtu(lp, null);
7811// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007812 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007813 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7814 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007815
Erik Klineb9888902016-04-05 13:30:49 +09007816 updateRoutes(newLp, oldLp, netId);
7817 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007818 // Make sure LinkProperties represents the latest private DNS status.
7819 // This does not need to be done before updateDnses because the
7820 // LinkProperties are not the source of the private DNS configuration.
7821 // updateDnses will fetch the private DNS configuration from DnsManager.
7822 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007823
Chalard Jean5b409c72021-02-04 13:12:59 +09007824 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007825 handleApplyDefaultProxy(newLp.getHttpProxy());
7826 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007827 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007828 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007829
7830 updateWakeOnLan(newLp);
7831
Hai Shalome58bdc62021-01-11 18:45:34 -08007832 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7833 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7834 // does, it needs to be merged here.
7835 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7836 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007837
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007838 // TODO - move this check to cover the whole function
7839 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007840 synchronized (networkAgent) {
7841 networkAgent.linkProperties = newLp;
7842 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007843 // Start or stop DNS64 detection and 464xlat according to network state.
7844 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007845 // Notify NSS when relevant events happened. Currently, NSS only cares about
7846 // interface changed to update clat interfaces accounting.
7847 final boolean interfacesChanged = oldLp == null
7848 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7849 if (interfacesChanged) {
7850 notifyIfacesChangedForNetworkStats();
7851 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007852 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7853 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007854 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007855 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007856
7857 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007858 }
7859
Hai Shalome58bdc62021-01-11 18:45:34 -08007860 /**
7861 * @param naData captive portal data from NetworkAgent
7862 * @param apiData captive portal data from capport API
7863 */
7864 @Nullable
7865 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7866 CaptivePortalData apiData) {
7867 if (naData == null || apiData == null) {
7868 return naData == null ? apiData : naData;
7869 }
7870 final CaptivePortalData.Builder captivePortalBuilder =
7871 new CaptivePortalData.Builder(naData);
7872
7873 if (apiData.isCaptive()) {
7874 captivePortalBuilder.setCaptive(true);
7875 }
7876 if (apiData.isSessionExtendable()) {
7877 captivePortalBuilder.setSessionExtendable(true);
7878 }
7879 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7880 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7881 // otherwise data would be inconsistent. Prefer the capport API info if present,
7882 // as it can generally be refreshed more often.
7883 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7884 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7885 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7886 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7887 // No source has time / bytes remaining information: surface the newest refresh time
7888 // for other fields
7889 captivePortalBuilder.setRefreshTime(
7890 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7891 }
7892
Hai Shalom7c6ab402021-02-04 19:34:06 -08007893 // Prioritize the user portal URL from the network agent if the source is authenticated.
7894 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7895 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7896 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7897 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007898 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007899 // Prioritize the venue information URL from the network agent if the source is
7900 // authenticated.
7901 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7902 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7903 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7904 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007905 }
7906 return captivePortalBuilder.build();
7907 }
7908
Suprabh Shukla1e312032023-01-24 03:36:37 -08007909 private String makeNflogPrefix(String iface, long networkHandle) {
7910 // This needs to be kept in sync and backwards compatible with the decoding logic in
7911 // NetdEventListenerService, which is non-mainline code.
7912 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
7913 }
7914
7915 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007916 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007917 // marks on unsupported interfaces is harmless.
Suprabh Shukla1e312032023-01-24 03:36:37 -08007918 if (!nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007919 return;
7920 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007921
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007922 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7923 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7924
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007925 // Mask/mark of zero will not detect anything interesting.
7926 // Don't install rules unless both values are nonzero.
7927 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007928 return;
7929 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007930
Suprabh Shukla1e312032023-01-24 03:36:37 -08007931 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007932 try {
7933 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007934 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007935 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007936 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007937 }
7938 } catch (Exception e) {
7939 loge("Exception modifying wakeup packet monitoring: " + e);
7940 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007941 }
7942
Junyu Lai970963e2022-10-25 15:46:47 +08007943 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09007944 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08007945 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09007946 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08007947 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09007948 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007949 for (final String iface : interfaceDiff.added) {
7950 try {
7951 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007952 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08007953 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007954 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08007955 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007956 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007957 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007958 }
Paul Jensenbff73492014-04-28 10:33:11 -04007959 }
7960 }
Chalard Jean9589e722019-11-19 19:03:53 +09007961 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007962 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007963 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08007964 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007965 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007966 } catch (Exception e) {
7967 loge("Exception removing interface: " + e);
7968 }
7969 }
7970 }
7971
Tyler Weare4314862019-12-05 14:55:30 -08007972 // TODO: move to frameworks/libs/net.
7973 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7974 final String nextHop;
7975
7976 switch (route.getType()) {
7977 case RouteInfo.RTN_UNICAST:
7978 if (route.hasGateway()) {
7979 nextHop = route.getGateway().getHostAddress();
7980 } else {
7981 nextHop = INetd.NEXTHOP_NONE;
7982 }
7983 break;
7984 case RouteInfo.RTN_UNREACHABLE:
7985 nextHop = INetd.NEXTHOP_UNREACHABLE;
7986 break;
7987 case RouteInfo.RTN_THROW:
7988 nextHop = INetd.NEXTHOP_THROW;
7989 break;
7990 default:
7991 nextHop = INetd.NEXTHOP_NONE;
7992 break;
7993 }
7994
7995 final RouteInfoParcel rip = new RouteInfoParcel();
7996 rip.ifName = route.getInterface();
7997 rip.destination = route.getDestination().toString();
7998 rip.nextHop = nextHop;
7999 rip.mtu = route.getMtu();
8000
8001 return rip;
8002 }
8003
Paul Jensene0fd4a82014-08-06 15:51:33 -04008004 /**
8005 * Have netd update routes from oldLp to newLp.
8006 * @return true if routes changed between oldLp and newLp
8007 */
Junyu Lai970963e2022-10-25 15:46:47 +08008008 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8009 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008010 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008011 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8012 new CompareOrUpdateResult<>(
8013 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008014 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008015 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008016
8017 // add routes before removing old in case it helps with continuous connectivity
8018
Chalard Jean9dd11612018-06-04 16:52:49 +09008019 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008020 for (RouteInfo route : routeDiff.added) {
8021 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008022 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008023 try {
Tyler Weare4314862019-12-05 14:55:30 -08008024 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008025 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008026 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008027 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008028 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008029 }
8030 }
8031 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008032 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008033 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008034 try {
Tyler Weare4314862019-12-05 14:55:30 -08008035 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008036 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008037 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008038 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008039 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008040 }
8041 }
8042
8043 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008044 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008045 try {
Tyler Weare4314862019-12-05 14:55:30 -08008046 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008047 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008048 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008049 }
8050 }
Tyler Weare4314862019-12-05 14:55:30 -08008051
8052 for (RouteInfo route : routeDiff.updated) {
8053 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8054 try {
8055 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8056 } catch (Exception e) {
8057 loge("Exception in networkUpdateRouteParcel: " + e);
8058 }
8059 }
8060 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8061 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008062 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008063
Junyu Lai970963e2022-10-25 15:46:47 +08008064 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8065 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008066 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8067 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008068 }
Erik Klineb9888902016-04-05 13:30:49 +09008069
Erik Kline31b4a9e2018-01-11 21:07:29 +09008070 if (DBG) {
8071 final Collection<InetAddress> dnses = newLp.getDnsServers();
8072 log("Setting DNS servers for network " + netId + " to " + dnses);
8073 }
Erik Klineb9888902016-04-05 13:30:49 +09008074 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008075 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008076 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008077 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008078 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008079 }
Erik Kline54e35c02017-04-07 15:29:29 +09008080 }
8081
Junyu Lai970963e2022-10-25 15:46:47 +08008082 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8083 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008084 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8085 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008086 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8087 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008088
8089 if (!wasFiltering && !needsFiltering) {
8090 // Nothing to do.
8091 return;
8092 }
8093
8094 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8095 // Nothing changed.
8096 return;
8097 }
8098
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008099 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008100 if (ranges == null || ranges.isEmpty()) {
8101 return;
8102 }
8103
Qingxi Libb8da982020-01-17 17:54:27 -08008104 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008105 // TODO: this create a window of opportunity for apps to receive traffic between the time
8106 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008107 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008108 // old rules are being removed.
8109 if (wasFiltering) {
8110 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8111 }
8112 if (needsFiltering) {
8113 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8114 }
8115 }
8116
Valentin Iftime9fa35092019-09-24 13:32:13 +02008117 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008118 if (mWolSupportedInterfaces == null) {
8119 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008120 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008121 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008122 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8123 }
8124
Luke Huangb913c812018-08-24 20:33:16 +08008125 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008126 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008127 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008128 }
8129 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008130 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008131 }
Luke Huangb913c812018-08-24 20:33:16 +08008132 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008133 }
8134
Chalard Jean62edfd82019-12-02 18:39:29 +09008135 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8136 @NonNull final NetworkCapabilities newNc) {
8137 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8138 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008139 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008140 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008141 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008142 } catch (RemoteException | ServiceSpecificException e) {
8143 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008144 }
8145 }
8146 }
8147
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008148 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008149 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008150 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008151 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008152 underlyingNetworks = underlyingNetworksOrDefault(
8153 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008154 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008155 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8156 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008157 // metered if any underlying is metered, or originally declared metered by the agent.
8158 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008159 boolean roaming = false; // roaming if any underlying is roaming
8160 boolean congested = false; // congested if any underlying is congested
8161 boolean suspended = true; // suspended if all underlying are suspended
8162
8163 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008164 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008165 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008166 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008167 for (Network underlyingNetwork : underlyingNetworks) {
8168 final NetworkAgentInfo underlying =
8169 getNetworkAgentInfoForNetwork(underlyingNetwork);
8170 if (underlying == null) continue;
8171
8172 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8173 hadUnderlyingNetworks = true;
8174 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008175 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008176 }
8177
8178 // Merge capabilities of this underlying network. For bandwidth, assume the
8179 // worst case.
8180 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8181 underlyingCaps.getLinkDownstreamBandwidthKbps());
8182 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8183 underlyingCaps.getLinkUpstreamBandwidthKbps());
8184 // If this underlying network is metered, the VPN is metered (it may cost money
8185 // to send packets on this network).
8186 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8187 // If this underlying network is roaming, the VPN is roaming (the billing structure
8188 // is different than the usual, local one).
8189 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8190 // If this underlying network is congested, the VPN is congested (the current
8191 // condition of the network affects the performance of this network).
8192 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8193 // If this network is not suspended, the VPN is not suspended (the VPN
8194 // is able to transfer some data).
8195 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008196 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008197 }
8198 }
8199 if (!hadUnderlyingNetworks) {
8200 // No idea what the underlying networks are; assume reasonable defaults
8201 metered = true;
8202 roaming = false;
8203 congested = false;
8204 suspended = false;
8205 }
8206
Chalard Jean1d420b32022-10-12 16:39:37 +09008207 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008208 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8209 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8210 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8211 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8212 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8213 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008214 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008215 }
8216
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008217 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008218 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8219 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8220 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008221 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008222 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008223 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008224 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008225 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8226 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008227 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008228 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008229 if (nai.everConnected()
8230 && !nai.isVPN()
8231 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008232 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008233 // does not cause any request (that is not a listen) currently matching that agent to
8234 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008235 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008236 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008237 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008238 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008239 }
8240
Paul Jensen53f08952015-06-16 14:27:36 -04008241 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008242 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008243 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008244 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008245 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008246 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008247 }
Chalard Jean254bd162022-08-25 13:04:51 +09008248 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008249 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008250 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008251 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008252 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008253 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008254 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008255 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008256 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008257 }
Chalard Jean254bd162022-08-25 13:04:51 +09008258 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008259 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8260 } else {
8261 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8262 }
lucasline117e2e2019-10-22 18:27:33 +08008263 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008264
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008265 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008266 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8267 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008268 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008269 }
8270
Lorenzo Colittibd079452021-07-02 11:47:57 +09008271 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008272 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008273 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008274 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008275 }
8276
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008277 return newNc;
8278 }
8279
Lorenzo Colitti44840702021-01-11 22:27:57 +09008280 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8281 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8282 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8283 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8284 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8285 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8286 if (prevSuspended != suspended) {
8287 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8288 // onResumed have been removed.
8289 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8290 : ConnectivityManager.CALLBACK_RESUMED);
8291 }
8292 if (prevSuspended != suspended || prevRoaming != roaming) {
8293 // updateNetworkInfo will mix in the suspended info from the capabilities and
8294 // take appropriate action for the network having possibly changed state.
8295 updateNetworkInfo(nai, nai.networkInfo);
8296 }
8297 }
8298
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008299 /**
8300 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8301 *
8302 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8303 * capabilities we manage and store in {@code nai}, such as validated status and captive
8304 * portal status)
8305 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8306 * potentially triggers rematches.
8307 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8308 * change.)
8309 *
8310 * @param oldScore score of the network before any of the changes that prompted us
8311 * to call this function.
8312 * @param nai the network having its capabilities updated.
8313 * @param nc the new network capabilities.
8314 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008315 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008316 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008317 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008318 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008319 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8320 if (null != differences) {
8321 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8322 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008323 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008324 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008325
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008326 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008327 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008328 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008329
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008330 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008331 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8332 // the change we're processing can't affect any requests, it can only affect the listens
8333 // on this network. We might have been called by rematchNetworkAndRequests when a
8334 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008335 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008336 } else {
8337 // If the requestable capabilities have changed or the score changed, we can't have been
8338 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008339 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008340 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008341 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008342 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008343
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008344 final boolean oldMetered = prevNc.isMetered();
8345 final boolean newMetered = newNc.isMetered();
8346 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008347
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008348 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008349 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8350 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008351 }
junyulaif2c67e42018-08-07 19:50:45 +08008352
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008353 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8354 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008355
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008356 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008357 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008358 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008359 }
8360
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008361 // This network might have been underlying another network. Propagate its capabilities.
8362 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008363
8364 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008365 mDnsManager.updateTransportsForNetwork(
8366 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008367 }
lucaslin53e8a262021-06-08 01:43:59 +08008368
8369 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008370 }
8371
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008372 /** Convenience method to update the capabilities for a given network. */
8373 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008374 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008375 }
8376
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008377 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008378 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008379 *
8380 * Ingress interface filtering enforces that all apps under the given network can only receive
8381 * packets from the network's interface (and loopback). This is important for VPNs because
8382 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8383 * non-VPN interfaces.
8384 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008385 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008386 * 1. the network is an app VPN (not legacy VPN)
8387 * 2. the VPN does not allow bypass
8388 * 3. the VPN is fully-routed
8389 * 4. the VPN interface is non-null
8390 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008391 * @see INetd#firewallAddUidInterfaceRules
8392 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008393 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008394 @Nullable
8395 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008396 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008397 if (nc == null || lp == null) return null;
8398 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008399 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008400 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008401 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008402 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008403 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008404 && !lp.hasExcludeRoute()) {
8405 return lp.getInterfaceName();
8406 }
8407 return null;
8408 }
8409
8410 /**
8411 * Returns whether we need to set interface filtering rule or not
8412 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008413 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008414 String isolationIface) {
8415 // Allow rules are always needed if VPN isolation is enabled.
8416 if (isolationIface != null) return true;
8417
8418 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8419 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8420 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8421 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008422 }
8423
Chiachang Wang28afaff2020-12-10 22:24:47 +08008424 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8425 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8426 int index = 0;
8427 for (UidRange range : ranges) {
8428 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8429 index++;
8430 }
8431 return stableRanges;
8432 }
8433
Chalard Jeane6c95272022-01-25 21:04:21 +09008434 private static UidRangeParcel[] intsToUidRangeStableParcels(
8435 final @NonNull ArraySet<Integer> uids) {
8436 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8437 int index = 0;
8438 for (int uid : uids) {
8439 stableRanges[index] = new UidRangeParcel(uid, uid);
8440 index++;
8441 }
8442 return stableRanges;
8443 }
8444
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008445 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8446 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8447 for (int i = 0; i < ranges.length; i++) {
8448 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8449 }
8450 return stableRanges;
8451 }
8452
Ken Chen5e65a852020-12-24 12:59:10 +08008453 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8454 int[] exemptUids) {
8455 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8456 try {
8457 mNetd.socketDestroy(ranges, exemptUids);
8458 } catch (Exception e) {
8459 loge("Exception in socket destroy: ", e);
8460 }
8461 }
8462 }
8463
paulhuaa0743d2021-05-26 21:56:03 +08008464 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008465 int[] exemptUids = new int[2];
8466 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8467 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8468 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8469 exemptUids[0] = VPN_UID;
8470 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8471 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8472
Motomu Utsumi6345e462023-03-13 13:24:50 +09008473 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Ken Chen5e65a852020-12-24 12:59:10 +08008474 maybeCloseSockets(nai, ranges, exemptUids);
8475 try {
8476 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008477 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008478 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008479 } else {
paulhu0e79d952021-06-09 16:11:35 +08008480 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008481 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008482 }
8483 } catch (Exception e) {
8484 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8485 " on netId " + nai.network.netId + ". " + e);
8486 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008487 // Close sockets that established connection while requesting netd.
Ken Chen5e65a852020-12-24 12:59:10 +08008488 maybeCloseSockets(nai, ranges, exemptUids);
8489 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008490
lucaslin53e8a262021-06-08 01:43:59 +08008491 private boolean isProxySetOnAnyDefaultNetwork() {
8492 ensureRunningOnConnectivityServiceThread();
8493 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8494 final NetworkAgentInfo nai = nri.getSatisfier();
8495 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8496 return true;
8497 }
8498 }
8499 return false;
8500 }
8501
8502 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8503 NetworkCapabilities newNc) {
8504 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8505 // the proxy might be changed since the default network satisfied by the apps might also
8506 // changed.
8507 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8508 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008509 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8510 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008511 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008512 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8513 mProxyTracker.sendProxyBroadcast();
8514 }
8515 }
8516
Chalard Jeane6c95272022-01-25 21:04:21 +09008517 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8518 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008519 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8520 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008521 if (null == prevRanges) prevRanges = new ArraySet<>();
8522 if (null == newRanges) newRanges = new ArraySet<>();
8523 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8524
8525 prevRanges.removeAll(newRanges);
8526 newRanges.removeAll(prevRangesCopy);
8527
8528 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008529 // When updating the VPN uid routing rules, add the new range first then remove the old
8530 // range. If old range were removed first, there would be a window between the old
8531 // range being removed and the new range being added, during which UIDs contained
8532 // in both ranges are not subject to any VPN routing rules. Adding new range before
8533 // removing old range works because, unlike the filtering rules below, it's possible to
8534 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008535 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8536 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8537 // [1-5] & [1-2],[4-5] == [3]
8538 // Then we can do:
8539 // maybeCloseSockets([3])
8540 // mNetd.networkAddUidRanges([1-2],[4-5])
8541 // mNetd.networkRemoveUidRanges([1-5])
8542 // maybeCloseSockets([3])
8543 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8544 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008545 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008546 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008547 }
8548 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008549 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008550 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008551 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8552 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008553 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8554 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008555 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008556 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008557 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8558 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8559 // were added first and then newRanges got removed later, there would be only one uid
8560 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8561 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8562 // Note that this is in contrast with the (more robust) update of VPN routing rules
8563 // above, where the addition of new ranges happens before the removal of old ranges.
8564 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8565 // to be removed will never overlap with the new range to be added.
8566 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008567 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8568 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008569 }
8570 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008571 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008572 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008573 } catch (Exception e) {
8574 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008575 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008576 }
8577 }
8578
Chalard Jeande665262022-02-25 16:12:12 +09008579 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008580 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8581 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008582 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8583 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008584 if (prevEmpty && newEmpty) return;
8585
8586 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008587 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008588 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008589 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008590
8591 if (prevUids.equals(newUids)) return;
8592
8593 // This implementation is very simple and vastly faster for sets of Integers than
8594 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8595 // a key computed from the value and has storage for that.
8596 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8597 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8598 toRemove.removeAll(newUids);
8599 toAdd.removeAll(prevUids);
8600
8601 try {
8602 if (!toAdd.isEmpty()) {
8603 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8604 nai.network.netId,
8605 intsToUidRangeStableParcels(toAdd),
8606 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8607 }
8608 if (!toRemove.isEmpty()) {
8609 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8610 nai.network.netId,
8611 intsToUidRangeStableParcels(toRemove),
8612 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8613 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008614 } catch (ServiceSpecificException e) {
8615 // Has the interface disappeared since the network was built ?
8616 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008617 } catch (RemoteException e) {
8618 // Netd died. This usually causes a runtime restart anyway.
8619 }
8620 }
8621
Junyu Lai2ed7d412022-10-07 16:52:21 +08008622 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8623 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008624 ensureRunningOnConnectivityServiceThread();
8625
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008626 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008627 // Ignore updates for disconnected networks
8628 return;
8629 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008630 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008631 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008632 + "; created=" + nai.getCreatedTime()
8633 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008634 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008635 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8636 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008637 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008638 }
8639
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008640 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8641 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008642 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008643 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008644 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008645 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8646 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8647 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008648 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8649 // need to be sent as a separate extra.
8650 final NetworkRequest req = nri.isMultilayerRequest()
8651 ? nri.getActiveRequest()
8652 // Non-multilayer listen requests do not have an active request
8653 : nri.mRequests.get(0);
8654 if (req == null) {
8655 Log.wtf(TAG, "No request in NRI " + nri);
8656 }
8657 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008658 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008659 sendIntent(nri.mPendingIntent, intent);
8660 }
8661 // else not handled
8662 }
8663
Michael Groover73f69482023-01-27 11:01:25 -06008664 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
8665 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008666 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8667 mPendingIntentWakeLock.acquire();
8668 try {
8669 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008670 final BroadcastOptions options = BroadcastOptions.makeBasic();
8671 if (SdkLevel.isAtLeastT()) {
8672 // Explicitly disallow the receiver from starting activities, to prevent apps from
8673 // utilizing the PendingIntent as a backdoor to do this.
8674 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8675 }
8676 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8677 null /* requiredPermission */,
8678 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008679 } catch (PendingIntent.CanceledException e) {
8680 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8681 mPendingIntentWakeLock.release();
8682 releasePendingNetworkRequest(pendingIntent);
8683 }
8684 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8685 }
8686
8687 @Override
8688 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8689 String resultData, Bundle resultExtras) {
8690 if (DBG) log("Finished sending " + pendingIntent);
8691 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008692 // Release with a delay so the receiving client has an opportunity to put in its
8693 // own request.
8694 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008695 }
8696
Chalard Jean46bfbf02022-02-02 00:56:25 +09008697 // networkAgent is only allowed to be null if notificationType is
8698 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8699 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008700 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008701 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008702 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008703 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008704 // Default request has no msgr. Also prevents callbacks from being invoked for
8705 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8706 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8707 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008708 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008709 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008710 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008711 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008712 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008713 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008714 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008715 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8716 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008717 }
Roshan Pius951c0032020-12-22 15:10:42 -08008718 final boolean includeLocationSensitiveInfo =
8719 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008720 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008721 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008722 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008723 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008724 networkCapabilitiesRestrictedForCallerPermissions(
8725 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8726 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008727 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008728 nri.mCallingAttributionTag);
8729 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008730 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8731 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008732 // For this notification, arg1 contains the blocked status.
8733 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008734 break;
8735 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008736 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008737 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008738 break;
8739 }
8740 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008741 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008742 final NetworkCapabilities netCap =
8743 networkCapabilitiesRestrictedForCallerPermissions(
8744 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8745 putParcelable(
8746 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008747 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008748 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008749 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008750 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008751 break;
8752 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008753 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008754 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8755 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008756 break;
8757 }
junyulaif2c67e42018-08-07 19:50:45 +08008758 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008759 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008760 msg.arg1 = arg1;
8761 break;
8762 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008763 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008764 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008765 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008766 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008767 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008768 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008769 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008770 }
James Mattis45d81842021-01-10 14:24:24 -08008771 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008772 } catch (RemoteException e) {
8773 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008774 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008775 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008776 }
8777
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008778 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8779 bundle.putParcelable(t.getClass().getSimpleName(), t);
8780 }
8781
Chalard Jean0702f982021-09-16 21:50:07 +09008782 /**
8783 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8784 *
8785 * When a request should be assigned to a new network, it is normally lingered to give
8786 * time for apps to gracefully migrate their connections. When both networks are on the same
8787 * radio, but that radio can't do time-sharing efficiently, this may end up being
8788 * counter-productive because any traffic on the old network may drastically reduce the
8789 * performance of the new network.
8790 * The stack supports a configuration to let modem vendors state that their radio can't
8791 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8792 * from one cell network to another can't be done gracefully.
8793 *
8794 * @param oldNai the old network serving the request
8795 * @param newNai the new network serving the request
8796 * @return whether the switch can be graceful
8797 */
8798 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8799 @NonNull final NetworkAgentInfo newSatisfier) {
8800 if (mCellularRadioTimesharingCapable) return true;
8801 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8802 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8803 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8804 }
8805
Paul Jensenaf94b982014-09-30 15:37:41 -04008806 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008807 if (nai.numRequestNetworkRequests() != 0) {
8808 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8809 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008810 // Ignore listening and track default requests.
8811 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008812 loge("Dead network still had at least " + nr);
8813 break;
8814 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008815 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008816 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008817 }
8818
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008819 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8820 if (oldNetwork == null) {
8821 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8822 return;
8823 }
Chalard Jean49707572019-12-10 21:07:02 +09008824 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008825
8826 // If we get here it means that the last linger timeout for this network expired. So there
8827 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008828 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008829
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008830 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008831 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008832 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008833 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008834 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008835 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008836 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008837 }
8838
James Mattise3ef1912020-12-20 11:09:58 -08008839 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8840 boolean isDefaultChanged = false;
8841 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8842 final NetworkReassignment.RequestReassignment reassignment =
8843 changes.getReassignment(defaultRequestInfo);
8844 if (null == reassignment) {
8845 continue;
8846 }
8847 // reassignment only contains those instances where the satisfying network changed.
8848 isDefaultChanged = true;
8849 // Notify system services of the new default.
8850 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8851 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008852
James Mattise3ef1912020-12-20 11:09:58 -08008853 if (isDefaultChanged) {
8854 // Hold a wakelock for a short time to help apps in migrating to a new default.
8855 scheduleReleaseNetworkTransitionWakelock();
8856 }
8857 }
8858
8859 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8860 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8861 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8862 if (DBG) {
8863 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8864 }
Chalard Jean8e382112019-12-03 20:45:30 +09008865
James Mattisd31bdfa2020-12-23 16:37:26 -08008866 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8867 if (newDefaultNetwork != null) {
8868 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008869 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008870
James Mattisd31bdfa2020-12-23 16:37:26 -08008871 // Set an app level managed default and return since further processing only applies to the
8872 // default network.
8873 if (mDefaultRequest != nri) {
8874 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8875 return;
8876 }
8877
8878 makeDefaultNetwork(newDefaultNetwork);
8879
James Mattise3ef1912020-12-20 11:09:58 -08008880 if (oldDefaultNetwork != null) {
8881 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8882 }
8883 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008884 handleApplyDefaultProxy(null != newDefaultNetwork
8885 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8886 updateTcpBufferSizes(null != newDefaultNetwork
8887 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008888 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008889 }
8890
James Mattisd31bdfa2020-12-23 16:37:26 -08008891 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8892 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8893 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8894 try {
8895 if (VDBG) {
8896 log("Setting default network for " + nri
8897 + " using UIDs " + nri.getUids()
8898 + " with old network " + (oldDefaultNetwork != null
8899 ? oldDefaultNetwork.network().getNetId() : "null")
8900 + " and new network " + (newDefaultNetwork != null
8901 ? newDefaultNetwork.network().getNetId() : "null"));
8902 }
8903 if (nri.getUids().isEmpty()) {
8904 throw new IllegalStateException("makeDefaultForApps called without specifying"
8905 + " any applications to set as the default." + nri);
8906 }
8907 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008908 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008909 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008910 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008911 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008912 }
8913 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008914 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008915 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008916 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008917 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008918 }
8919 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008920 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008921 }
8922 }
8923
Junyu Lai35665cc2022-12-19 17:37:48 +08008924 /**
8925 * Collect restricted uid ranges for the given network and UserHandle, these uids
8926 * are not restricted for matched enterprise networks but being restricted for non-matched
8927 * enterprise networks and non-enterprise networks.
8928 */
8929 @NonNull
8930 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
8931 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
8932 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
8933 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
8934 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
8935
8936 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
8937 // The NC is built from a `ProfileNetworkPreference` which has only one
8938 // enterprise ID, so it's guaranteed to have exactly one.
8939 final int prefId = pref.capabilities.getEnterpriseIds()[0];
8940 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
8941 continue;
8942 }
8943 }
8944
8945 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
8946 pref.capabilities.getUidRanges())) {
8947 throw new IllegalArgumentException(
8948 "Overlapping uid range in preference: " + pref);
8949 }
8950 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
8951 }
8952 return restrictedUidRanges;
8953 }
8954
8955 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08008956 // Netd command is not implemented before U.
8957 if (!SdkLevel.isAtLeastU()) return;
8958
Junyu Lai35665cc2022-12-19 17:37:48 +08008959 ensureRunningOnConnectivityServiceThread();
8960 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
8961 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
8962 .getUserHandles(true /* excludeDying */);
8963 if (users.isEmpty()) {
8964 throw new IllegalStateException("No user is available");
8965 }
8966
8967 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8968 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
8969 for (final UserHandle user : users) {
8970 final ArraySet<UidRange> restrictedUidRanges =
8971 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
8972 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
8973 UidRange.createForUser(user), restrictedUidRanges));
8974 }
8975
8976 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
8977 configs.add(new NativeUidRangeConfig(
8978 nai.network.netId, rangesParcel, 0 /* subPriority */));
8979 }
8980
8981 // The netd API replaces the previous configs with the current configs.
8982 // Thus, for network disconnection or preference removal, no need to
8983 // unset previous config. Instead, collecting all currently needed
8984 // configs and issue to netd.
8985 try {
8986 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
8987 } catch (ServiceSpecificException e) {
8988 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08008989 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08008990 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08008991 // Netd died. This will cause a runtime restart anyway.
8992 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08008993 }
8994 }
8995
James Mattisd31bdfa2020-12-23 16:37:26 -08008996 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8997 try {
8998 if (null != newDefaultNetwork) {
8999 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9000 } else {
9001 mNetd.networkClearDefault();
9002 }
9003 } catch (RemoteException | ServiceSpecificException e) {
9004 loge("Exception setting default network :" + e);
9005 }
9006 }
9007
Chalard Jean05cbe972019-12-09 11:50:38 +09009008 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009009 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009010 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009011 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009012 processNewlySatisfiedListenRequests(nai);
9013 }
9014
9015 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009016 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9017 if (nri.isMultilayerRequest()) {
9018 continue;
9019 }
9020 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009021 if (!nr.isListen()) continue;
9022 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009023 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009024 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9025 }
9026 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009027 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009028
Chalard Jeancd397a22019-11-22 22:33:33 +09009029 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009030 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9031 if (nri.isMultilayerRequest()) {
9032 continue;
9033 }
9034 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009035 if (!nr.isListen()) continue;
9036 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9037 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009038 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009039 }
9040 }
9041 }
9042
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009043 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009044 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009045 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009046 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009047 @Nullable public final NetworkRequest mOldNetworkRequest;
9048 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009049 @Nullable public final NetworkAgentInfo mOldNetwork;
9050 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009051 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009052 @Nullable final NetworkRequest oldNetworkRequest,
9053 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009054 @Nullable final NetworkAgentInfo oldNetwork,
9055 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009056 mNetworkRequestInfo = networkRequestInfo;
9057 mOldNetworkRequest = oldNetworkRequest;
9058 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009059 mOldNetwork = oldNetwork;
9060 mNewNetwork = newNetwork;
9061 }
Chalard Jean49707572019-12-10 21:07:02 +09009062
9063 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009064 final NetworkRequest requestToShow = null != mNewNetworkRequest
9065 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9066 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009067 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9068 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009069 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009070 }
9071
Chalard Jean46a62372019-12-10 21:25:24 +09009072 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009073
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009074 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009075 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009076 }
9077
9078 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009079 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009080 // The code is never supposed to add two reassignments of the same request. Make
9081 // sure this stays true, but without imposing this expensive check on all
9082 // reassignments on all user devices.
9083 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009084 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009085 throw new IllegalStateException("Trying to reassign ["
9086 + reassignment + "] but already have ["
9087 + existing + "]");
9088 }
9089 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009090 }
Chalard Jean46a62372019-12-10 21:25:24 +09009091 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009092 }
9093
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009094 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009095 // the passed request.
9096 @Nullable
9097 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009098 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009099 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009100 }
9101 return null;
9102 }
Chalard Jean49707572019-12-10 21:07:02 +09009103
9104 public String toString() {
9105 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9106 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009107 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009108 for (final RequestReassignment rr : getRequestReassignments()) {
9109 sj.add(rr.toString());
9110 }
9111 return sj.toString();
9112 }
9113
9114 public String debugString() {
9115 final StringBuilder sb = new StringBuilder();
9116 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009117 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009118 for (final RequestReassignment rr : getRequestReassignments()) {
9119 sb.append("\n ").append(rr);
9120 }
9121 return sb.append("\n").toString();
9122 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009123 }
9124
Chalard Jean24344d72019-12-04 13:32:31 +09009125 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009126 @Nullable final NetworkRequest previousRequest,
9127 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009128 @Nullable final NetworkAgentInfo previousSatisfier,
9129 @Nullable final NetworkAgentInfo newSatisfier,
9130 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009131 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009132 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009133 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009134 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009135 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009136 }
James Mattisa076c532020-12-02 14:12:41 -08009137 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009138 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009139 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009140 // If this network switch can't be supported gracefully, the request is not
9141 // lingered. This allows letting go of the network sooner to reclaim some
9142 // performance on the new network, since the radio can't do both at the same
9143 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009144 //
9145 // Also don't linger the request if the old network has been destroyed.
9146 // A destroyed network does not provide actual network connectivity, so
9147 // lingering it is not useful. In particular this ensures that a destroyed
9148 // network is outscored by its replacement,
9149 // then it is torn down immediately instead of being lingered, and any apps that
9150 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009151 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9152 }
Chalard Jean24344d72019-12-04 13:32:31 +09009153 } else {
9154 if (VDBG || DDBG) log(" accepting network in place of null");
9155 }
junyulai0ac374f2020-12-14 18:41:52 +08009156
9157 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9158 // and immediately satisfies a request then remove the timer. This will happen for
9159 // all networks except in the case of an underlying network for a VCN.
9160 if (newSatisfier.isNascent()) {
9161 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009162 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009163 }
9164
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009165 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009166 newSatisfier.unlingerRequest(newRequest.requestId);
9167 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009168 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009169 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009170 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009171 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009172 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009173 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009174 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009175 }
James Mattisa076c532020-12-02 14:12:41 -08009176 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009177 }
James Mattisa076c532020-12-02 14:12:41 -08009178 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009179 }
9180
James Mattisa076c532020-12-02 14:12:41 -08009181 /**
9182 * This function is triggered when something can affect what network should satisfy what
9183 * request, and it computes the network reassignment from the passed collection of requests to
9184 * network match to the one that the system should now have. That data is encoded in an
9185 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9186 * satisfier.
9187 *
9188 * After the reassignment is computed, it is applied to the state objects.
9189 *
9190 * @param networkRequests the nri objects to evaluate for possible network reassignment
9191 * @return NetworkReassignment listing of proposed network assignment changes
9192 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009193 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009194 private NetworkReassignment computeNetworkReassignment(
9195 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009196 final NetworkReassignment changes = new NetworkReassignment();
9197
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009198 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009199 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009200 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009201 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009202 }
Chalard Jean857a1712019-12-10 21:08:07 +09009203
James Mattisa076c532020-12-02 14:12:41 -08009204 for (final NetworkRequestInfo nri : networkRequests) {
9205 // Non-multilayer listen requests can be ignored.
9206 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9207 continue;
9208 }
9209 NetworkAgentInfo bestNetwork = null;
9210 NetworkRequest bestRequest = null;
9211 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009212 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009213 // Stop evaluating as the highest possible priority request is satisfied.
9214 if (null != bestNetwork) {
9215 bestRequest = req;
9216 break;
9217 }
9218 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009219 if (null == bestNetwork && isDefaultBlocked(nri)) {
9220 // Remove default networking if disallowed for managed default requests.
9221 bestNetwork = mNoServiceNetwork;
9222 }
9223 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009224 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009225 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009226 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009227 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009228 }
9229 return changes;
9230 }
9231
James Mattisa076c532020-12-02 14:12:41 -08009232 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9233 return new HashSet<>(mNetworkRequests.values());
9234 }
9235
Paul Jensenc88b39b2015-06-16 14:27:36 -04009236 /**
James Mattisa076c532020-12-02 14:12:41 -08009237 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009238 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009239 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009240 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009241 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9242 }
9243
9244 /**
9245 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9246 * being disconnected.
9247 */
9248 private void rematchNetworksAndRequests(
9249 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9250 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009251 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009252 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009253 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009254 final long computed = SystemClock.elapsedRealtime();
9255 applyNetworkReassignment(changes, start);
9256 final long applied = SystemClock.elapsedRealtime();
9257 issueNetworkNeeds();
9258 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009259 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009260 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9261 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009262 log(changes.debugString());
9263 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009264 // Shorter form, only one line of log
9265 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9266 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009267 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009268 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009269
Chalard Jeand7f762d2019-12-10 19:01:29 +09009270 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009271 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009272 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009273
9274 // Since most of the time there are only 0 or 1 background networks, it would probably
9275 // be more efficient to just use an ArrayList here. TODO : measure performance
9276 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9277 for (final NetworkAgentInfo nai : nais) {
9278 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9279 }
9280
Chalard Jeand7f762d2019-12-10 19:01:29 +09009281 // First, update the lists of satisfied requests in the network agents. This is necessary
9282 // because some code later depends on this state to be correct, most prominently computing
9283 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009284 for (final NetworkReassignment.RequestReassignment event :
9285 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009286 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9287 event.mOldNetworkRequest, event.mNewNetworkRequest,
9288 event.mOldNetwork, event.mNewNetwork,
9289 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009290 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009291
James Mattise3ef1912020-12-20 11:09:58 -08009292 // Process default network changes if applicable.
9293 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009294
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009295 // Notify requested networks are available after the default net is switched, but
9296 // before LegacyTypeTracker sends legacy broadcasts
9297 for (final NetworkReassignment.RequestReassignment event :
9298 changes.getRequestReassignments()) {
9299 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009300 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009301 } else {
James Mattisa076c532020-12-02 14:12:41 -08009302 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009303 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009304 }
9305 }
9306
junyulai0ac374f2020-12-14 18:41:52 +08009307 // Update the inactivity state before processing listen callbacks, because the background
9308 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009309 // just yet though, because they have to be sent after the listens are processed to keep
9310 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009311 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009312 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009313 // Rematching may have altered the inactivity state of some networks, so update all
9314 // inactivity timers. updateInactivityState reads the state from the network agent
9315 // and does nothing if the state has not changed : the source of truth is controlled
9316 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9317 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009318 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009319 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009320 }
9321 }
9322
Chalard Jeanb10ab412019-12-11 14:12:30 +09009323 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009324 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009325 // Process listen requests and update capabilities if the background state has
9326 // changed for this network. For consistency with previous behavior, send onLost
9327 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009328 processNewlyLostListenRequests(nai);
9329 if (oldBackground != nai.isBackgroundNetwork()) {
9330 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009331 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009332 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009333 }
9334
junyulai0ac374f2020-12-14 18:41:52 +08009335 for (final NetworkAgentInfo nai : inactiveNetworks) {
9336 // For nascent networks, if connecting with no foreground request, skip broadcasting
9337 // LOSING for backward compatibility. This is typical when mobile data connected while
9338 // wifi connected with mobile data always-on enabled.
9339 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009340 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009341 }
9342
James Mattise3ef1912020-12-20 11:09:58 -08009343 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009344
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009345 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009346 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009347 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009348 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009349 // This network has active linger timers and no requests, but is not
9350 // lingering. Linger it.
9351 //
9352 // One way (the only way?) this can happen if this network is unvalidated
9353 // and became unneeded due to another network improving its score to the
9354 // point where this network will no longer be able to satisfy any requests
9355 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009356 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009357 notifyNetworkLosing(nai, now);
9358 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009359 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009360 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009361 teardownUnneededNetwork(nai);
9362 }
9363 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009364 }
9365 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009366
Chalard Jean62edfd82019-12-02 18:39:29 +09009367 /**
9368 * Apply a change in background state resulting from rematching networks with requests.
9369 *
9370 * During rematch, a network may change background states by starting to satisfy or stopping
9371 * to satisfy a foreground request. Listens don't count for this. When a network changes
9372 * background states, its capabilities need to be updated and callbacks fired for the
9373 * capability change.
9374 *
9375 * @param nai The network that changed background states
9376 */
9377 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9378 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9379 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9380 updateNetworkPermissions(nai, newNc);
9381 nai.getAndSetNetworkCapabilities(newNc);
9382 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9383 }
9384
Chalard Jeanf0344532019-11-19 19:23:38 +09009385 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009386 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009387 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009388 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9389 changes.getReassignment(mDefaultRequest);
9390 final NetworkAgentInfo oldDefaultNetwork =
9391 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9392 final NetworkAgentInfo newDefaultNetwork =
9393 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009394
Chalard Jean5b409c72021-02-04 13:12:59 +09009395 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009396 // Maintain the illusion : since the legacy API only understands one network at a time,
9397 // if the default network changed, apps should see a disconnected broadcast for the
9398 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009399 if (oldDefaultNetwork != null) {
9400 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9401 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009402 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009403 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009404 // The new default network can be newly null if and only if the old default
9405 // network doesn't satisfy the default request any more because it lost a
9406 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009407 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009408 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009409 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009410 }
9411 }
9412
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009413 // Now that all the callbacks have been sent, send the legacy network broadcasts
9414 // as needed. This is necessary so that legacy requests correctly bind dns
9415 // requests to this network. The legacy users are listening for this broadcast
9416 // and will generally do a dns request so they can ensureRouteToHost and if
9417 // they do that before the callbacks happen they'll use the default network.
9418 //
9419 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9420 // callbacks, but if apps can receive the broadcast before the callback, they still might
9421 // have an inconsistent view of networking.
9422 //
9423 // This *does* introduce a race where if the user uses the new api
9424 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9425 // they may get old info. Reverse this after the old startUsing api is removed.
9426 // This is on top of the multiple intent sequencing referenced in the todo above.
9427 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009428 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009429 addNetworkToLegacyTypeTracker(nai);
9430 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009431 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009432 }
9433
Chalard Jean0354d8c2021-01-12 10:58:56 +09009434 private void issueNetworkNeeds() {
9435 ensureRunningOnConnectivityServiceThread();
9436 for (final NetworkOfferInfo noi : mNetworkOffers) {
9437 issueNetworkNeeds(noi);
9438 }
9439 }
9440
9441 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9442 ensureRunningOnConnectivityServiceThread();
9443 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9444 informOffer(nri, noi.offer, mNetworkRanker);
9445 }
9446 }
9447
9448 /**
9449 * Inform a NetworkOffer about any new situation of a request.
9450 *
9451 * This function handles updates to offers. A number of events may happen that require
9452 * updating the registrant for this offer about the situation :
9453 * • The offer itself was updated. This may lead the offer to no longer being able
9454 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9455 * or conversely being strengthened enough to beat the satisfier (and therefore
9456 * start being needed)
9457 * • The network satisfying a request changed (including cases where the request
9458 * starts or stops being satisfied). The new network may be a stronger or weaker
9459 * match than the old one, possibly affecting whether the offer is needed.
9460 * • The network satisfying a request updated their score. This may lead the offer
9461 * to no longer be able to beat it if the current satisfier got better, or
9462 * conversely start being a good choice if the current satisfier got weaker.
9463 *
9464 * @param nri The request
9465 * @param offer The offer. This may be an updated offer.
9466 */
9467 private static void informOffer(@NonNull NetworkRequestInfo nri,
9468 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9469 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9470 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009471
9472 // Multi-layer requests have a currently active request, the one being satisfied.
9473 // Since the system will try to bring up a better network than is currently satisfying
9474 // the request, NetworkProviders need to be told the offers matching the requests *above*
9475 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9476 // not needed, and the offer is needed for the active request iff the offer can beat
9477 // the satisfier.
9478 // For non-multilayer requests, the logic above gracefully degenerates to only the
9479 // last case.
9480 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9481 // providers that the offer is needed for this request, until the active request is found.
9482 // In a second phase, deal with the currently active request. In a third phase, inform
9483 // the providers that offer is unneeded for the remaining requests.
9484
9485 // First phase : inform providers of all requests above the active request.
9486 int i;
9487 for (i = 0; nri.mRequests.size() > i; ++i) {
9488 final NetworkRequest request = nri.mRequests.get(i);
9489 if (activeRequest == request) break; // Found the active request : go to phase 2
9490 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9491 // Since this request is higher-priority than the one currently satisfied, if the
9492 // offer can satisfy it, the provider should try and bring up the network for sure ;
9493 // no need to even ask the ranker – an offer that can satisfy is always better than
9494 // no network. Hence tell the provider so unless it already knew.
9495 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9496 offer.onNetworkNeeded(request);
9497 }
9498 }
9499
9500 // Second phase : deal with the active request (if any)
9501 if (null != activeRequest && activeRequest.isRequest()) {
9502 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009503 // If an offer can satisfy the request, it is considered needed if it is currently
9504 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009505 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009506 && satisfier.factorySerialNumber == offer.providerId
9507 && activeRequest.canBeSatisfiedBy(offer.caps);
9508 final boolean newNeeded = currentlyServing
9509 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009510 if (newNeeded != oldNeeded) {
9511 if (newNeeded) {
9512 offer.onNetworkNeeded(activeRequest);
9513 } else {
9514 // The offer used to be able to beat the satisfier. Now it can't.
9515 offer.onNetworkUnneeded(activeRequest);
9516 }
9517 }
9518 }
9519
9520 // Third phase : inform the providers that the offer isn't needed for any request
9521 // below the active one.
9522 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9523 final NetworkRequest request = nri.mRequests.get(i);
9524 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9525 // Since this request is lower-priority than the one currently satisfied, if the
9526 // offer can satisfy it, the provider should not try and bring up the network.
9527 // Hence tell the provider so unless it already knew.
9528 if (offer.neededFor(request)) {
9529 offer.onNetworkUnneeded(request);
9530 }
9531 }
9532 }
9533
Chalard Jean61c79252019-11-07 23:07:32 +09009534 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9535 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9536 NetworkRequest nr = nai.requestAt(i);
9537 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9538 // legacy type tracker filters out repeat adds
9539 mLegacyTypeTracker.add(nr.legacyType, nai);
9540 }
9541 }
9542
9543 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009544 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009545 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9546 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9547 if (nai.isVPN()) {
9548 mLegacyTypeTracker.add(TYPE_VPN, nai);
9549 }
9550 }
9551
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009552 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009553 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009554 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009555 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009556 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009557 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009558
Chalard Jean254bd162022-08-25 13:04:51 +09009559 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009560 // Don't repeat publish.
9561 if (newInetCondition == mDefaultInetConditionPublished) return;
9562
9563 mDefaultInetConditionPublished = newInetCondition;
9564 sendInetConditionBroadcast(nai.networkInfo);
9565 }
9566
Chalard Jeand61375d2020-01-14 22:46:36 +09009567 @NonNull
9568 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9569 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009570 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009571 final boolean suspended =
9572 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9573 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9574 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9575 // state. This is because the network could have been suspended before connecting,
9576 // or it could be disconnecting while being suspended, and in both these cases
9577 // the state should not be overridden. Note that the only detailed state that
9578 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9579 // worry about multiple different substates of CONNECTED.
9580 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9581 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009582 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9583 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9584 // network agent is created, then goes to suspended, then goes out of suspended without
9585 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009586 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009587 ? NetworkInfo.DetailedState.CONNECTED
9588 : NetworkInfo.DetailedState.CONNECTING,
9589 info.getReason(),
9590 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009591 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009592 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009593 return newInfo;
9594 }
9595
9596 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9597 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9598
Erik Kline99f301b2017-02-15 19:59:17 +09009599 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009600 NetworkInfo oldInfo = null;
9601 synchronized (networkAgent) {
9602 oldInfo = networkAgent.networkInfo;
9603 networkAgent.networkInfo = newInfo;
9604 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009605
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009606 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009607 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9608 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009609 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009610
Chalard Jean254bd162022-08-25 13:04:51 +09009611 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009612 && (state == NetworkInfo.State.CONNECTED
9613 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009614
9615 // A network that has just connected has zero requests and is thus a foreground network.
9616 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9617
Luke Huangfdd11f82019-04-09 18:41:49 +08009618 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009619 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009620 // Initialize the network's capabilities to their starting values according to the
9621 // underlying networks. This ensures that the capabilities are correct before
9622 // anything happens to the network.
9623 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009624 }
Chalard Jean254bd162022-08-25 13:04:51 +09009625 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009626 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009627 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009628 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009629 }
9630
Chalard Jean254bd162022-08-25 13:04:51 +09009631 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9632 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009633
lucaslin45e639b2019-04-03 17:09:28 +08009634 // NetworkCapabilities need to be set before sending the private DNS config to
9635 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009636 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9637
Erik Kline9a62f012018-03-21 07:18:33 -07009638 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009639 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9640 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009641
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009642 // If a rate limit has been configured and is applicable to this network (network
9643 // provides internet connectivity), apply it. The tc police filter cannot be attached
9644 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9645 // updateInterfaces -> INetd#networkAddInterface.
9646 // Note: in case of a system server crash, the NetworkController constructor in netd
9647 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9648 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9649 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9650 mIngressRateLimit);
9651 }
9652
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009653 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9654 // command must be sent after updating LinkProperties to maximize chances of
9655 // NetworkMonitor seeing the correct LinkProperties when starting.
9656 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009657 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009658 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009659 }
Chalard Jeand4900722022-02-06 12:25:38 +09009660 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9661 params.networkAgentConfig = networkAgent.networkAgentConfig;
9662 params.networkCapabilities = networkAgent.networkCapabilities;
9663 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9664 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009665 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9666 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9667 // call that would cause a Log.wtf to be emitted from the system_server process, and
9668 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9669 // process to check the interface version, just use an SDK check. NetworkStack will
9670 // always be new enough when running on T+.
9671 if (SdkLevel.isAtLeastT()) {
9672 networkAgent.networkMonitor().notifyNetworkConnected(params);
9673 } else {
9674 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9675 params.networkCapabilities);
9676 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009677 final long delay = activelyPreferBadWifi()
9678 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9679 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9680 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009681
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009682 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9683 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9684 // capabilities, so it only needs to be done once on initial connect, not every time the
9685 // network's capabilities change. Note that we do this before rematching the network,
9686 // so we could decide to tear it down immediately afterwards. That's fine though - on
9687 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9688 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009689 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009690
junyulai0ac374f2020-12-14 18:41:52 +08009691 // Before first rematching networks, put an inactivity timer without any request, this
9692 // allows {@code updateInactivityState} to update the state accordingly and prevent
9693 // tearing down for any {@code unneeded} evaluation in this period.
9694 // Note that the timer will not be rescheduled since the expiry time is
9695 // fixed after connection regardless of the network satisfying other requests or not.
9696 // But it will be removed as soon as the network satisfies a request for the first time.
9697 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9698 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009699 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009700
Paul Jensen05e85ee2014-09-11 11:00:39 -04009701 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009702 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009703
9704 // This has to happen after matching the requests, because callbacks are just requests.
9705 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009706 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009707 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009708 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009709 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009710 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009711 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009712 if (networkAgent.isVPN()) {
9713 // As the active or bound network changes for apps, broadcast the default proxy, as
9714 // apps may need to update their proxy data. This is called after disconnecting from
9715 // VPN to make sure we do not broadcast the old proxy data.
9716 // TODO(b/122649188): send the broadcast only to VPN users.
9717 mProxyTracker.sendProxyBroadcast();
9718 }
Chalard Jean254bd162022-08-25 13:04:51 +09009719 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9720 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009721 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009722 }
9723 }
9724
Chalard Jean28018572020-12-21 18:36:52 +09009725 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009726 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9727 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009728 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009729 }
9730
Erik Kline99f301b2017-02-15 19:59:17 +09009731 // Notify only this one new request of the current state. Transfer all the
9732 // current state by calling NetworkCapabilities and LinkProperties callbacks
9733 // so that callers can be guaranteed to have as close to atomicity in state
9734 // transfer as can be supported by this current API.
9735 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009736 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009737 if (nri.mPendingIntent != null) {
9738 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9739 // Attempt no subsequent state pushes where intents are involved.
9740 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009741 }
Erik Kline99f301b2017-02-15 19:59:17 +09009742
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009743 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009744 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009745 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9746 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9747 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009748 }
9749
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009750 // Notify the requests on this NAI that the network is now lingered.
9751 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009752 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009753 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9754 }
9755
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009756 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9757 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9758 return vpnBlocked
9759 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9760 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9761 }
9762
9763 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9764 if (blockedReasons == BLOCKED_REASON_NONE) {
9765 mUidBlockedReasons.delete(uid);
9766 } else {
9767 mUidBlockedReasons.put(uid, blockedReasons);
9768 }
9769 }
9770
junyulaif2c67e42018-08-07 19:50:45 +08009771 /**
9772 * Notify of the blocked state apps with a registered callback matching a given NAI.
9773 *
9774 * Unlike other callbacks, blocked status is different between each individual uid. So for
9775 * any given nai, all requests need to be considered according to the uid who filed it.
9776 *
9777 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009778 * @param oldMetered True if the previous network capabilities were metered.
9779 * @param newMetered True if the current network capabilities are metered.
9780 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9781 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009782 */
9783 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009784 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9785 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009786
9787 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9788 NetworkRequest nr = nai.requestAt(i);
9789 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009790
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009791 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9792 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9793 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009794 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009795 : oldVpnBlocked;
9796
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009797 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9798 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9799 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009800 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009801 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009802 }
9803 }
9804 }
9805
9806 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009807 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009808 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009809 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009810 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009811 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009812 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009813 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009814 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009815
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009816 final int oldBlockedState = getBlockedState(
9817 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9818 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9819 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009820 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009821 }
junyulaif2c67e42018-08-07 19:50:45 +08009822 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9823 NetworkRequest nr = nai.requestAt(i);
9824 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009825 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009826 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9827 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009828 }
9829 }
9830 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009831 }
9832
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009833 @VisibleForTesting
9834 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009835 // The NetworkInfo we actually send out has no bearing on the real
9836 // state of affairs. For example, if the default connection is mobile,
9837 // and a request for HIPRI has just gone away, we need to pretend that
9838 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9839 // the state to DISCONNECTED, even though the network is of type MOBILE
9840 // and is still connected.
9841 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9842 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009843 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009844 if (state != DetailedState.DISCONNECTED) {
9845 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009846 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009847 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009848 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009849 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9850 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9851 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9852 if (info.isFailover()) {
9853 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9854 nai.networkInfo.setFailover(false);
9855 }
9856 if (info.getReason() != null) {
9857 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9858 }
9859 if (info.getExtraInfo() != null) {
9860 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9861 }
9862 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009863 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009864 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009865 if (newDefaultAgent != null) {
9866 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9867 newDefaultAgent.networkInfo);
9868 } else {
9869 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9870 }
9871 }
9872 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9873 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009874 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009875 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009876 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009877 }
9878 }
9879 }
9880
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009881 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009882 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009883 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009884 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009885 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009886 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9887 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009888 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9889 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009890 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009891 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009892 } else {
9893 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9894 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009895 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009896 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009897
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009898 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9899 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9900 }
9901
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009902 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009903 * Returns the list of all interfaces that could be used by network traffic that does not
9904 * explicitly specify a network. This includes the default network, but also all VPNs that are
9905 * currently connected.
9906 *
9907 * Must be called on the handler thread.
9908 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009909 @NonNull
9910 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009911 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009912 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009913 final Set<Integer> activeNetIds = new ArraySet<>();
9914 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9915 if (nri.isBeingSatisfied()) {
9916 activeNetIds.add(nri.getSatisfier().network().netId);
9917 }
9918 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009919 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009920 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009921 defaultNetworks.add(nai.network);
9922 }
9923 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009924 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009925 }
9926
9927 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009928 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9929 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009930 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009931 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009932 ensureRunningOnConnectivityServiceThread();
9933 String activeIface = null;
9934 LinkProperties activeLinkProperties = getActiveLinkProperties();
9935 if (activeLinkProperties != null) {
9936 activeIface = activeLinkProperties.getInterfaceName();
9937 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009938
junyulai2050bed2021-01-23 09:46:34 +08009939 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009940 try {
junyulaide41fc22021-01-22 22:46:01 +08009941 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009942 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009943 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9944 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009945 } catch (Exception ignored) {
9946 }
9947 }
9948
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009949 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009950 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009951 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009952 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009953 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009954
9955 if (!TextUtils.isEmpty(settingUrl)) {
9956 return settingUrl;
9957 }
9958
9959 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009960 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009961 if (!TextUtils.isEmpty(settingUrl)) {
9962 return settingUrl;
9963 }
9964
9965 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009966 }
9967
9968 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009969 public void startNattKeepalive(Network network, int intervalSeconds,
9970 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009971 enforceKeepalivePermission();
9972 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009973 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00009974 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
9975 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +00009976 // false and set the underpinned network to null because there is no way and no
9977 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
9978 // deprecated method.
9979 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009980 }
9981
9982 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009983 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009984 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +00009985 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -07009986 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009987 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009988 mKeepaliveTracker.startNattKeepalive(
9989 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +00009990 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
9991 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -07009992 } finally {
9993 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9994 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009995 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9996 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009997 }
9998 }
junyulaid05a1922019-01-15 11:32:44 +08009999 }
10000
10001 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010002 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010003 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010004 try {
10005 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010006 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010007 mKeepaliveTracker.startTcpKeepalive(
10008 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10009 } finally {
10010 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10011 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010012 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10013 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010014 }
10015 }
junyulai0835a1e2019-01-08 20:04:33 +080010016 }
10017
10018 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010019 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010020 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010021 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10022 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010023 }
10024
10025 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010026 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010027 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010028
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010029 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010030 final long token = Binder.clearCallingIdentity();
10031 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010032 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10033 UserHandle.getUserHandleForUid(uid))) {
10034 return;
10035 }
10036
Heemin Seogdb8489d2019-06-12 09:21:44 -070010037 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10038 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010039
10040 // Turn airplane mode off
10041 setAirplaneMode(false);
10042
10043 // restore private DNS settings to default mode (opportunistic)
10044 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10045 UserHandle.getUserHandleForUid(uid))) {
10046 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10047 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10048 }
10049
10050 Settings.Global.putString(mContext.getContentResolver(),
10051 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010052 } finally {
10053 Binder.restoreCallingIdentity(token);
10054 }
Stuart Scottd5463642015-04-02 18:00:02 -070010055 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010056
Ricky Wai7097cc92018-01-23 04:09:45 +000010057 @Override
10058 public byte[] getNetworkWatchlistConfigHash() {
10059 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10060 if (nwm == null) {
10061 loge("Unable to get NetworkWatchlistManager");
10062 return null;
10063 }
10064 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10065 return nwm.getWatchlistConfigHash();
10066 }
10067
Hugo Benichibe0c7652016-05-31 16:28:06 +090010068 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010069 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010070 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010071 }
Hugo Benichif4210292017-04-21 15:07:12 +090010072
10073 private static boolean toBool(int encodedBoolean) {
10074 return encodedBoolean != 0; // Only 0 means false.
10075 }
10076
10077 private static int encodeBool(boolean b) {
10078 return b ? 1 : 0;
10079 }
mswest4632928412018-03-12 10:34:34 -070010080
10081 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010082 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10083 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10084 @NonNull String[] args) {
10085 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10086 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010087 }
10088
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010089 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010090 @Override
10091 public int onCommand(String cmd) {
10092 if (cmd == null) {
10093 return handleDefaultCommands(cmd);
10094 }
10095 final PrintWriter pw = getOutPrintWriter();
10096 try {
10097 switch (cmd) {
10098 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010099 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10100 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010101 final String action = getNextArg();
10102 if ("enable".equals(action)) {
10103 setAirplaneMode(true);
10104 return 0;
10105 } else if ("disable".equals(action)) {
10106 setAirplaneMode(false);
10107 return 0;
10108 } else if (action == null) {
10109 final ContentResolver cr = mContext.getContentResolver();
10110 final int enabled = Settings.Global.getInt(cr,
10111 Settings.Global.AIRPLANE_MODE_ON);
10112 pw.println(enabled == 0 ? "disabled" : "enabled");
10113 return 0;
10114 } else {
10115 onHelp();
10116 return -1;
10117 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010118 case "reevaluate":
10119 // Usage : adb shell cmd connectivity reevaluate <netId>
10120 // If netId is omitted, then reevaluate the default network
10121 final String netId = getNextArg();
10122 final NetworkAgentInfo nai;
10123 if (null == netId) {
10124 // Note that the command is running on the wrong thread to call this,
10125 // so this could in principle return stale data. But it can't crash.
10126 nai = getDefaultNetwork();
10127 } else {
10128 // If netId can't be parsed, this throws NumberFormatException, which
10129 // is passed back to adb who prints it.
10130 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10131 }
10132 if (null == nai) {
10133 pw.println("Unknown network (net ID not found or no default network)");
10134 return 0;
10135 }
10136 Log.d(TAG, "Reevaluating network " + nai.network);
10137 reportNetworkConnectivity(nai.network, !nai.isValidated());
10138 return 0;
mswest4632928412018-03-12 10:34:34 -070010139 default:
10140 return handleDefaultCommands(cmd);
10141 }
10142 } catch (Exception e) {
10143 pw.println(e);
10144 }
10145 return -1;
10146 }
10147
10148 @Override
10149 public void onHelp() {
10150 PrintWriter pw = getOutPrintWriter();
10151 pw.println("Connectivity service commands:");
10152 pw.println(" help");
10153 pw.println(" Print this help text.");
10154 pw.println(" airplane-mode [enable|disable]");
10155 pw.println(" Turn airplane mode on or off.");
10156 pw.println(" airplane-mode");
10157 pw.println(" Get airplane mode.");
10158 }
10159 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010160
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010161 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010162 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10163 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10164 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010165 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010166 }
10167
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010168 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10169 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010170 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10171 final TransportInfo newInfo = nc.getTransportInfo();
10172 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10173 return;
10174 }
10175 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010176 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010177 }
10178 }
10179
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010180 /**
10181 * @param connectionInfo the connection to resolve.
10182 * @return {@code uid} if the connection is found and the app has permission to observe it
10183 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10184 * connection is not found.
10185 */
10186 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010187 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10188 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10189 }
10190
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010191 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010192 connectionInfo.local, connectionInfo.remote);
10193
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010194 if (uid == INVALID_UID) return uid; // Not found.
10195
10196 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10197 // VPN, if any, that applies to the UID that owns the connection.
10198 if (checkNetworkStackPermission()) return uid;
10199
10200 final NetworkAgentInfo vpn = getVpnForUid(uid);
10201 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010202 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010203 return INVALID_UID;
10204 }
10205
10206 return uid;
10207 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010208
Benedict Wong493e04b2018-11-09 14:45:34 -080010209 /**
10210 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10211 *
10212 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10213 */
10214 @Override
10215 public IBinder startOrGetTestNetworkService() {
10216 synchronized (mTNSLock) {
10217 TestNetworkService.enforceTestNetworkPermissions(mContext);
10218
10219 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010220 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010221 }
10222
10223 return mTNS;
10224 }
10225 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010226
Cody Kesting73708bf2019-12-18 10:57:50 -080010227 /**
10228 * Handler used for managing all Connectivity Diagnostics related functions.
10229 *
10230 * @see android.net.ConnectivityDiagnosticsManager
10231 *
10232 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10233 */
10234 @VisibleForTesting
10235 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010236 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10237
Cody Kesting73708bf2019-12-18 10:57:50 -080010238 /**
10239 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10240 * android.net.ConnectivityDiagnosticsManager}.
10241 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10242 * NetworkRequestInfo to be registered
10243 */
10244 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10245
10246 /**
10247 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10248 * android.net.ConnectivityDiagnosticsManager}.
10249 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10250 * arg1 = the uid of the caller
10251 */
10252 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10253
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010254 /**
10255 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010256 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010257 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10258 * NetworkMonitor.
10259 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010260 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010261 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010262
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010263 /**
10264 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10265 * been detected on the network.
10266 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10267 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10268 * arg2 = NetID.
10269 * data = PersistableBundle of extras passed from NetworkMonitor.
10270 */
10271 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10272
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010273 /**
10274 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10275 * the platform. This event will invoke {@link
10276 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10277 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010278 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010279 */
10280 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10281
Cody Kesting73708bf2019-12-18 10:57:50 -080010282 private ConnectivityDiagnosticsHandler(Looper looper) {
10283 super(looper);
10284 }
10285
10286 @Override
10287 public void handleMessage(Message msg) {
10288 switch (msg.what) {
10289 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10290 handleRegisterConnectivityDiagnosticsCallback(
10291 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10292 break;
10293 }
10294 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10295 handleUnregisterConnectivityDiagnosticsCallback(
10296 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10297 break;
10298 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010299 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010300 final ConnectivityReportEvent reportEvent =
10301 (ConnectivityReportEvent) msg.obj;
10302
Aaron Huang959d3642021-01-21 15:47:41 +080010303 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010304 break;
10305 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010306 case EVENT_DATA_STALL_SUSPECTED: {
10307 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010308 final Pair<Long, PersistableBundle> arg =
10309 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010310 if (nai == null) break;
10311
Aaron Huang959d3642021-01-21 15:47:41 +080010312 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010313 break;
10314 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010315 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010316 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010317 break;
10318 }
10319 default: {
10320 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10321 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010322 }
10323 }
10324 }
10325
10326 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10327 @VisibleForTesting
10328 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10329 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10330 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010331 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010332
10333 @VisibleForTesting
10334 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010335 @NonNull IConnectivityDiagnosticsCallback cb,
10336 @NonNull NetworkRequestInfo nri,
10337 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010338 mCb = cb;
10339 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010340 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010341 }
10342
10343 @Override
10344 public void binderDied() {
10345 log("ConnectivityDiagnosticsCallback IBinder died.");
10346 unregisterConnectivityDiagnosticsCallback(mCb);
10347 }
10348 }
10349
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010350 /**
10351 * Class used for sending information from {@link
10352 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10353 */
10354 private static class NetworkTestedResults {
10355 private final int mNetId;
10356 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010357 @Nullable private final String mRedirectUrl;
10358
10359 private NetworkTestedResults(
10360 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10361 mNetId = netId;
10362 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010363 mRedirectUrl = redirectUrl;
10364 }
10365 }
10366
10367 /**
10368 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10369 * ConnectivityDiagnosticsHandler}.
10370 */
10371 private static class ConnectivityReportEvent {
10372 private final long mTimestampMillis;
10373 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010374 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010375
Aaron Huang959d3642021-01-21 15:47:41 +080010376 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10377 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010378 mTimestampMillis = timestampMillis;
10379 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010380 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010381 }
10382 }
10383
Cody Kestingf1120be2020-08-03 18:01:40 -070010384 /**
10385 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10386 * ConnectivityDiagnosticsHandler}.
10387 */
10388 private static class ReportedNetworkConnectivityInfo {
10389 public final boolean hasConnectivity;
10390 public final boolean isNetworkRevalidating;
10391 public final int reporterUid;
10392 @NonNull public final NetworkAgentInfo nai;
10393
10394 private ReportedNetworkConnectivityInfo(
10395 boolean hasConnectivity,
10396 boolean isNetworkRevalidating,
10397 int reporterUid,
10398 @NonNull NetworkAgentInfo nai) {
10399 this.hasConnectivity = hasConnectivity;
10400 this.isNetworkRevalidating = isNetworkRevalidating;
10401 this.reporterUid = reporterUid;
10402 this.nai = nai;
10403 }
10404 }
10405
Cody Kesting73708bf2019-12-18 10:57:50 -080010406 private void handleRegisterConnectivityDiagnosticsCallback(
10407 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10408 ensureRunningOnConnectivityServiceThread();
10409
10410 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010411 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010412 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10413
James Mattis64b8b0f2020-11-24 17:40:49 -080010414 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10415 // confusing for these networks to change when an NRI is satisfied in another layer.
10416 if (nri.isMultilayerRequest()) {
10417 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10418 + "network requests.");
10419 }
10420
Cody Kesting73708bf2019-12-18 10:57:50 -080010421 // This means that the client registered the same callback multiple times. Do
10422 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010423 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010424 if (VDBG) log("Diagnostics callback is already registered");
10425
10426 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10427 // incremented when the NetworkRequestInfo is created as part of
10428 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010429 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010430 return;
10431 }
10432
Cody Kesting31f1ff62020-03-05 10:46:02 -080010433 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010434
10435 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010436 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010437 } catch (RemoteException e) {
10438 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010439 return;
10440 }
10441
10442 // Once registered, provide ConnectivityReports for matching Networks
10443 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10444 synchronized (mNetworkForNetId) {
10445 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10446 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010447 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10448 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010449 matchingNetworks.add(nai);
10450 }
10451 }
10452 }
10453 for (final NetworkAgentInfo nai : matchingNetworks) {
10454 final ConnectivityReport report = nai.getConnectivityReport();
10455 if (report == null) {
10456 continue;
10457 }
10458 if (!checkConnectivityDiagnosticsPermissions(
10459 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10460 continue;
10461 }
10462
10463 try {
10464 cb.onConnectivityReportAvailable(report);
10465 } catch (RemoteException e) {
10466 // Exception while sending the ConnectivityReport. Move on to the next network.
10467 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010468 }
10469 }
10470
10471 private void handleUnregisterConnectivityDiagnosticsCallback(
10472 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10473 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010474 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010475
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010476 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10477 mConnectivityDiagnosticsCallbacks.remove(iCb);
10478 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010479 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10480 return;
10481 }
10482
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010483 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010484
Cody Kesting70fa2b22020-12-02 12:16:56 -080010485 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10486 // (if the Binder died)
10487 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10488 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010489 return;
10490 }
10491
Cody Kesting46cb1672020-03-04 13:35:20 -080010492 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10493 // incremented when the NetworkRequestInfo is created as part of
10494 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010495 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010496
Cody Kesting31f1ff62020-03-05 10:46:02 -080010497 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010498 }
10499
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010500 private void handleNetworkTestedWithExtras(
10501 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10502 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010503 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010504 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010505 final ConnectivityReport report =
10506 new ConnectivityReport(
10507 reportEvent.mNai.network,
10508 reportEvent.mTimestampMillis,
10509 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010510 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010511 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010512 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010513
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010514 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010515 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010516 for (final IConnectivityDiagnosticsCallback cb : results) {
10517 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010518 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010519 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010520 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010521 }
10522 }
10523 }
10524
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010525 private void handleDataStallSuspected(
10526 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10527 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010528 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010529 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010530 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010531 new DataStallReport(
10532 nai.network,
10533 timestampMillis,
10534 detectionMethod,
10535 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010536 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010537 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010538 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010539 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010540 for (final IConnectivityDiagnosticsCallback cb : results) {
10541 try {
10542 cb.onDataStallSuspected(report);
10543 } catch (RemoteException ex) {
10544 loge("Error invoking onDataStallSuspected", ex);
10545 }
10546 }
10547 }
10548
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010549 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010550 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10551 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10552 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10553
10554 // If the Network is being re-validated as a result of this call to
10555 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10556 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010557 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010558 getMatchingPermissionedCallbacks(
10559 nai,
10560 reportedNetworkConnectivityInfo.isNetworkRevalidating
10561 ? Process.INVALID_UID
10562 : reportedNetworkConnectivityInfo.reporterUid);
10563
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010564 for (final IConnectivityDiagnosticsCallback cb : results) {
10565 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010566 cb.onNetworkConnectivityReported(
10567 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010568 } catch (RemoteException ex) {
10569 loge("Error invoking onNetworkConnectivityReported", ex);
10570 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010571
10572 // If the Network isn't re-validating, also provide the cached report. If there is no
10573 // cached report, the Network is still being validated and a report will be sent once
10574 // validation is complete. Note that networks which never undergo validation will still
10575 // have a cached ConnectivityReport with RESULT_SKIPPED.
10576 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10577 try {
10578 cb.onConnectivityReportAvailable(cachedReport);
10579 } catch (RemoteException ex) {
10580 loge("Error invoking onConnectivityReportAvailable", ex);
10581 }
10582 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010583 }
10584 }
10585
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010586 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010587 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10588 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010589 sanitized.setUids(null);
10590 sanitized.setAdministratorUids(new int[0]);
10591 sanitized.setOwnerUid(Process.INVALID_UID);
10592 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010593 }
10594
Cody Kestingf1120be2020-08-03 18:01:40 -070010595 /**
10596 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10597 *
10598 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10599 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010600 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010601 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010602 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010603 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010604 mConnectivityDiagnosticsCallbacks.entrySet()) {
10605 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10606 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010607
James Mattis64b8b0f2020-11-24 17:40:49 -080010608 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010609 if (!nai.satisfies(nri.mRequests.get(0))) {
10610 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010611 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010612
10613 // UID for this callback must either be:
10614 // - INVALID_UID (which sends callbacks to all UIDs), or
10615 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10616 // notified as a result)
10617 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10618 continue;
10619 }
10620
10621 if (!checkConnectivityDiagnosticsPermissions(
10622 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10623 continue;
10624 }
10625
10626 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010627 }
10628 return results;
10629 }
10630
Cody Kesting7474f672021-05-11 14:22:40 -070010631 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10632 @NonNull NetworkAgentInfo nai) {
10633 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10634 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10635 }
10636
Cody Kesting160ef392021-05-05 13:17:22 -070010637 private boolean hasLocationPermission(String packageName, int uid) {
10638 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10639 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10640 // call in a try-catch.
10641 try {
10642 if (!mLocationPermissionChecker.checkLocationPermission(
10643 packageName, null /* featureId */, uid, null /* message */)) {
10644 return false;
10645 }
10646 } catch (SecurityException e) {
10647 return false;
10648 }
10649
10650 return true;
10651 }
10652
10653 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10654 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010655 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010656 && virtual.networkCapabilities.getOwnerUid() == uid
10657 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10658 return true;
10659 }
10660 }
10661
10662 return false;
10663 }
10664
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010665 @VisibleForTesting
10666 boolean checkConnectivityDiagnosticsPermissions(
10667 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10668 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10669 return true;
10670 }
10671
Cody Kesting160ef392021-05-05 13:17:22 -070010672 // Administrator UIDs also contains the Owner UID
10673 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10674 if (!CollectionUtils.contains(administratorUids, callbackUid)
10675 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010676 return false;
10677 }
10678
Cody Kesting7474f672021-05-11 14:22:40 -070010679 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10680 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010681 }
10682
Cody Kestingd199a9d2019-12-17 12:55:28 -080010683 @Override
10684 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010685 @NonNull IConnectivityDiagnosticsCallback callback,
10686 @NonNull NetworkRequest request,
10687 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010688 Objects.requireNonNull(callback, "callback must not be null");
10689 Objects.requireNonNull(request, "request must not be null");
10690 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10691
Cody Kesting73708bf2019-12-18 10:57:50 -080010692 if (request.legacyType != TYPE_NONE) {
10693 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10694 + " Please use NetworkCapabilities instead.");
10695 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010696 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010697 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010698
10699 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10700 // and administrator uids to be safe.
10701 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010702 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010703
10704 final NetworkRequest requestWithId =
10705 new NetworkRequest(
10706 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10707
10708 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10709 //
10710 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10711 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10712 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010713 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010714 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010715 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010716
10717 mConnectivityDiagnosticsHandler.sendMessage(
10718 mConnectivityDiagnosticsHandler.obtainMessage(
10719 ConnectivityDiagnosticsHandler
10720 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10721 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010722 }
10723
10724 @Override
10725 public void unregisterConnectivityDiagnosticsCallback(
10726 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010727 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010728 mConnectivityDiagnosticsHandler.sendMessage(
10729 mConnectivityDiagnosticsHandler.obtainMessage(
10730 ConnectivityDiagnosticsHandler
10731 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010732 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010733 0,
10734 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010735 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010736
10737 @Override
10738 public void simulateDataStall(int detectionMethod, long timestampMillis,
10739 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010740 Objects.requireNonNull(network, "network must not be null");
10741 Objects.requireNonNull(extras, "extras must not be null");
10742
paulhu3ffffe72021-09-16 10:15:22 +080010743 enforceAnyPermissionOf(mContext,
10744 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010745 android.Manifest.permission.NETWORK_STACK);
10746 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10747 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010748 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010749 }
10750
10751 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010752 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010753 throw new SecurityException("Data Stall simulation is only possible for network "
10754 + "creators");
10755 }
10756
Cody Kesting652e3ec2020-05-21 12:08:21 -070010757 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10758 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10759 // Data Stall information as a DataStallReportParcelable and passing to
10760 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10761 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010762 final DataStallReportParcelable p = new DataStallReportParcelable();
10763 p.timestampMillis = timestampMillis;
10764 p.detectionMethod = detectionMethod;
10765
10766 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10767 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10768 }
10769 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10770 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10771 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10772 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10773 }
10774
Serik Beketayevec8ad212020-12-07 22:43:07 -080010775 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010776 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010777
lucaslin66f44212021-02-23 01:12:55 +080010778 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10779 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010780 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010781 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010782 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010783 }
lucaslin37a16d92021-01-21 19:48:09 +080010784
10785 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010786 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010787 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010788 nai.clatd.interfaceLinkStateChanged(iface, up);
10789 }
10790 }
10791
10792 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010793 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010794 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010795 nai.clatd.interfaceRemoved(iface);
10796 }
lucaslin66f44212021-02-23 01:12:55 +080010797 }
10798 }
10799
lucaslin1a8b4c62021-01-21 02:02:55 +080010800 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10801
10802 /**
10803 * Class used for updating network activity tracking with netd and notify network activity
10804 * changes.
10805 */
10806 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010807 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010808 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010809 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010810 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10811 new RemoteCallbackList<>();
10812 // Indicate the current system default network activity is active or not.
10813 @GuardedBy("mActiveIdleTimers")
10814 private boolean mNetworkActive;
10815 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010816 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010817 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010818
Chalard Jean46bfbf02022-02-02 00:56:25 +090010819 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010820 public final int timeout;
10821 public final int transportType;
10822
10823 IdleTimerParams(int timeout, int transport) {
10824 this.timeout = timeout;
10825 this.transportType = transport;
10826 }
10827 }
10828
10829 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010830 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010831 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010832 mNetd = netd;
10833 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010834 }
10835
lucaslin66f44212021-02-23 01:12:55 +080010836 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10837 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10838 synchronized (mActiveIdleTimers) {
10839 mNetworkActive = active;
10840 // If there are no idle timers, it means that system is not monitoring
10841 // activity, so the system default network for those default network
10842 // unspecified apps is always considered active.
10843 //
10844 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10845 // any network activity change event. Whenever this event is received,
10846 // the mActiveIdleTimers should be always not empty. The legacy behavior
10847 // is no-op. Remove to refer to mNetworkActive only.
10848 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10849 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10850 }
10851 }
10852 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010853
lucaslin1193a5d2021-01-21 02:04:15 +080010854 // The network activity should only be updated from ConnectivityService handler thread
10855 // when mActiveIdleTimers lock is held.
10856 @GuardedBy("mActiveIdleTimers")
10857 private void reportNetworkActive() {
10858 final int length = mNetworkActivityListeners.beginBroadcast();
10859 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10860 try {
10861 for (int i = 0; i < length; i++) {
10862 try {
10863 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10864 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010865 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010866 }
10867 }
10868 } finally {
10869 mNetworkActivityListeners.finishBroadcast();
10870 }
10871 }
10872
10873 @GuardedBy("mActiveIdleTimers")
10874 public void handleReportNetworkActivity() {
10875 synchronized (mActiveIdleTimers) {
10876 reportNetworkActive();
10877 }
10878 }
10879
lucaslin1a8b4c62021-01-21 02:02:55 +080010880 // This is deprecated and only to support legacy use cases.
10881 private int transportTypeToLegacyType(int type) {
10882 switch (type) {
10883 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010884 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010885 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010886 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010887 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010888 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010889 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010890 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010891 default:
10892 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10893 }
10894 return ConnectivityManager.TYPE_NONE;
10895 }
10896
10897 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10898 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10899 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10900 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10901 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10902 final long ident = Binder.clearCallingIdentity();
10903 try {
10904 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10905 RECEIVE_DATA_ACTIVITY_CHANGE,
10906 null /* resultReceiver */,
10907 null /* scheduler */,
10908 0 /* initialCode */,
10909 null /* initialData */,
10910 null /* initialExtra */);
10911 } finally {
10912 Binder.restoreCallingIdentity(ident);
10913 }
10914 }
10915
10916 /**
10917 * Setup data activity tracking for the given network.
10918 *
10919 * Every {@code setupDataActivityTracking} should be paired with a
10920 * {@link #removeDataActivityTracking} for cleanup.
10921 */
10922 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10923 final String iface = networkAgent.linkProperties.getInterfaceName();
10924
10925 final int timeout;
10926 final int type;
10927
10928 if (networkAgent.networkCapabilities.hasTransport(
10929 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10930 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010931 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010932 10);
10933 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10934 } else if (networkAgent.networkCapabilities.hasTransport(
10935 NetworkCapabilities.TRANSPORT_WIFI)) {
10936 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010937 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010938 15);
10939 type = NetworkCapabilities.TRANSPORT_WIFI;
10940 } else {
10941 return; // do not track any other networks
10942 }
10943
lucaslinb961efc2021-01-21 02:03:17 +080010944 updateRadioPowerState(true /* isActive */, type);
10945
lucaslin1a8b4c62021-01-21 02:02:55 +080010946 if (timeout > 0 && iface != null) {
10947 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010948 synchronized (mActiveIdleTimers) {
10949 // Networks start up.
10950 mNetworkActive = true;
10951 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10952 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10953 reportNetworkActive();
10954 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010955 } catch (Exception e) {
10956 // You shall not crash!
10957 loge("Exception in setupDataActivityTracking " + e);
10958 }
10959 }
10960 }
10961
10962 /**
10963 * Remove data activity tracking when network disconnects.
10964 */
10965 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10966 final String iface = networkAgent.linkProperties.getInterfaceName();
10967 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10968
lucaslinb961efc2021-01-21 02:03:17 +080010969 if (iface == null) return;
10970
10971 final int type;
10972 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10973 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10974 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10975 type = NetworkCapabilities.TRANSPORT_WIFI;
10976 } else {
10977 return; // do not track any other networks
10978 }
10979
10980 try {
10981 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010982 synchronized (mActiveIdleTimers) {
10983 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10984 // The call fails silently if no idle timer setup for this interface
10985 mNetd.idletimerRemoveInterface(iface, params.timeout,
10986 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010987 }
lucaslinb961efc2021-01-21 02:03:17 +080010988 } catch (Exception e) {
10989 // You shall not crash!
10990 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010991 }
10992 }
10993
10994 /**
10995 * Update data activity tracking when network state is updated.
10996 */
10997 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10998 NetworkAgentInfo oldNetwork) {
10999 if (newNetwork != null) {
11000 setupDataActivityTracking(newNetwork);
11001 }
11002 if (oldNetwork != null) {
11003 removeDataActivityTracking(oldNetwork);
11004 }
11005 }
lucaslinb961efc2021-01-21 02:03:17 +080011006
11007 private void updateRadioPowerState(boolean isActive, int transportType) {
11008 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11009 switch (transportType) {
11010 case NetworkCapabilities.TRANSPORT_CELLULAR:
11011 bs.reportMobileRadioPowerState(isActive, NO_UID);
11012 break;
11013 case NetworkCapabilities.TRANSPORT_WIFI:
11014 bs.reportWifiRadioPowerState(isActive, NO_UID);
11015 break;
11016 default:
11017 logw("Untracked transport type:" + transportType);
11018 }
11019 }
lucaslin1193a5d2021-01-21 02:04:15 +080011020
11021 public boolean isDefaultNetworkActive() {
11022 synchronized (mActiveIdleTimers) {
11023 // If there are no idle timers, it means that system is not monitoring activity,
11024 // so the default network is always considered active.
11025 //
11026 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
11027 // tracking is disabled (negative idle timer value configured), or no active default
11028 // network. In the latter case, this reports active but it should report inactive.
11029 return mNetworkActive || mActiveIdleTimers.isEmpty();
11030 }
11031 }
11032
11033 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11034 mNetworkActivityListeners.register(l);
11035 }
11036
11037 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11038 mNetworkActivityListeners.unregister(l);
11039 }
lucaslin012f7a12021-01-21 02:04:35 +080011040
11041 public void dump(IndentingPrintWriter pw) {
11042 synchronized (mActiveIdleTimers) {
11043 pw.print("mNetworkActive="); pw.println(mNetworkActive);
11044 pw.println("Idle timers:");
11045 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
11046 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11047 final IdleTimerParams params = ent.getValue();
11048 pw.print(" timeout="); pw.print(params.timeout);
11049 pw.print(" type="); pw.println(params.transportType);
11050 }
11051 }
11052 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011053 }
James Mattis47db0582021-01-01 14:13:35 -080011054
Daniel Brightf9e945b2020-06-15 16:10:01 -070011055 /**
11056 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11057 *
11058 * @param socketInfo the socket information
11059 * @param callback the callback to register
11060 */
11061 @Override
11062 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11063 @NonNull final IQosCallback callback) {
11064 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11065 if (nai == null || nai.networkCapabilities == null) {
11066 try {
11067 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11068 } catch (final RemoteException ex) {
11069 loge("registerQosCallbackInternal: RemoteException", ex);
11070 }
11071 return;
11072 }
11073 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11074 }
11075
11076 /**
11077 * Register a {@link IQosCallback} with base {@link QosFilter}.
11078 *
11079 * @param filter the filter to register
11080 * @param callback the callback to register
11081 * @param nai the agent information related to the filter's network
11082 */
11083 @VisibleForTesting
11084 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11085 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011086 Objects.requireNonNull(filter, "filter must be non-null");
11087 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011088
11089 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011090 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11091 // on this network is unregistered when the app loses permission or b) no QoS
11092 // callbacks are sent for restricted networks unless the app currently has permission
11093 // to access restricted networks.
11094 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011095 }
11096 mQosCallbackTracker.registerCallback(callback, filter, nai);
11097 }
11098
11099 /**
11100 * Unregisters the given callback.
11101 *
11102 * @param callback the callback to unregister
11103 */
11104 @Override
11105 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011106 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011107 mQosCallbackTracker.unregisterCallback(callback);
11108 }
James Mattis47db0582021-01-01 14:13:35 -080011109
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011110 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11111 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11112 // Enterprise device can be fully managed like device owner and such use case
11113 // also should be supported. Calling app check for work profile and fully managed device
11114 // is already done in DevicePolicyManager.
11115 // This check is an extra caution to be sure device is fully managed or not.
11116 final UserManager um = mContext.getSystemService(UserManager.class);
11117 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11118 if (um.isManagedProfile(profile.getIdentifier())) {
11119 return true;
11120 }
11121 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
11122 return false;
11123 }
11124
James Mattis45d81842021-01-10 14:24:24 -080011125 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011126 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011127 *
11128 * See the documentation for the individual preferences for a description of the supported
11129 * behaviors.
11130 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011131 * @param profile If the device owner is set, any profile is allowed.
11132 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011133 * @param preferences the list of profile network preferences for the
11134 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011135 * @param listener an optional listener to listen for completion of the operation.
11136 */
11137 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011138 public void setProfileNetworkPreferences(
11139 @NonNull final UserHandle profile,
11140 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011141 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011142 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011143 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011144
11145 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011146 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11147 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11148 .build();
11149 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011150 }
11151
paulhu3ffffe72021-09-16 10:15:22 +080011152 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011153 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011154 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011155 }
11156 if (profile.getIdentifier() < 0) {
11157 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11158 + "UserHandle.CURRENT not supported)");
11159 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011160 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11161 throw new IllegalArgumentException("Profile must be a managed profile "
11162 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011163 }
paulhuaa0743d2021-05-26 21:56:03 +080011164
Chalard Jean0606fc82022-12-14 20:34:43 +090011165 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011166 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011167 for (final ProfileNetworkPreference preference : preferences) {
11168 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011169 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011170 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011171 switch (preference.getPreference()) {
11172 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11173 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011174 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011175 if (preference.getPreferenceEnterpriseId() != 0) {
11176 throw new IllegalArgumentException(
11177 "Invalid enterprise identifier in setProfileNetworkPreferences");
11178 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011179 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011180 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11181 blockingNonEnterprise = true;
11182 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011183 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11184 allowFallback = false;
11185 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011186 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011187 // This code is needed even though there is a check later on,
11188 // because isRangeAlreadyInPreferenceList assumes that every preference
11189 // has a UID list.
11190 if (hasDefaultPreference) {
11191 throw new IllegalArgumentException(
11192 "Default profile preference should not be set along with other "
11193 + "preference");
11194 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011195 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11196 throw new IllegalArgumentException(
11197 "Invalid enterprise identifier in setProfileNetworkPreferences");
11198 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011199 final Set<UidRange> uidRangeSet =
11200 getUidListToBeAppliedForNetworkPreference(profile, preference);
11201 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11202 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11203 } else {
11204 throw new IllegalArgumentException(
11205 "Overlapping uid range in setProfileNetworkPreferences");
11206 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011207 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011208 nc.addEnterpriseId(
11209 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011210 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11211 break;
11212 default:
11213 throw new IllegalArgumentException(
11214 "Invalid preference in setProfileNetworkPreferences");
11215 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011216 preferenceList.add(new ProfileNetworkPreferenceInfo(
11217 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011218 if (hasDefaultPreference && preferenceList.size() > 1) {
11219 throw new IllegalArgumentException(
11220 "Default profile preference should not be set along with other preference");
11221 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011222 }
11223 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011224 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011225 }
11226
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011227 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11228 @NonNull final UserHandle profile,
11229 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11230 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011231 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11232 profileNetworkPreference.getIncludedUids());
11233
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011234 if (uidRangeSet.size() > 0) {
11235 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11236 throw new IllegalArgumentException(
11237 "Allow uid range is outside the uid range of profile.");
11238 }
11239 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011240 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011241 profileNetworkPreference.getExcludedUids());
11242 if (disallowUidRangeSet.size() > 0) {
11243 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11244 throw new IllegalArgumentException(
11245 "disallow uid range is outside the uid range of profile.");
11246 }
11247 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11248 disallowUidRangeSet);
11249 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011250 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011251 uidRangeSet.add(profileUids);
11252 }
11253 }
11254 return uidRangeSet;
11255 }
11256
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011257 private boolean isEnterpriseIdentifierValid(
11258 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011259 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011260 return true;
11261 }
11262 return false;
11263 }
11264
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011265 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011266 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011267 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011268 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011269 // The NRI for a user should contain the request for capabilities.
11270 // If fallback to default network is needed then NRI should include
11271 // the request for the default network. Create an image of it to
11272 // have the correct UIDs in it (also a request can only be part of one NRI, because
11273 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011274 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11275 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011276 if (pref.allowFallback) {
11277 nrs.add(createDefaultInternetRequestForTransport(
11278 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11279 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011280 if (VDBG) {
11281 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11282 pref.capabilities.getUids()));
11283 }
11284
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011285 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011286 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011287 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011288 result.add(nri);
11289 }
11290 return result;
11291 }
11292
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011293 /**
11294 * Compare if the given UID range sets have the same UIDs.
11295 *
11296 */
11297 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011298 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011299 @NonNull Set<UidRange> uidRangeSet) {
11300 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11301 return false;
11302 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011303 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011304 if (UidRangeUtils.doesRangeSetOverlap(
11305 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11306 return true;
11307 }
11308 }
11309 return false;
11310 }
11311
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011312 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011313 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011314 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011315 /*
11316 * handleSetProfileNetworkPreference is always called for single user.
11317 * preferenceList only contains preferences for different uids within the same user
11318 * (enforced by getUidListToBeAppliedForNetworkPreference).
11319 * Clear all the existing preferences for the user before applying new preferences.
11320 *
11321 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011322 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11323 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011324 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11325 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011326
paulhu74128522021-09-28 02:29:03 +000011327 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11328 addPerAppDefaultNetworkRequests(
11329 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011330 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011331
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011332 // Finally, rematch.
11333 rematchAllNetworksAndRequests();
11334
11335 if (null != listener) {
11336 try {
11337 listener.onComplete();
11338 } catch (RemoteException e) {
11339 loge("Listener for setProfileNetworkPreference has died");
11340 }
11341 }
11342 }
11343
paulhu51f77dc2021-06-07 02:34:20 +000011344 @VisibleForTesting
11345 @NonNull
11346 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11347 @NonNull final Set<Integer> uids) {
11348 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11349 if (uids.size() == 0) {
11350 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11351 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11352 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11353 return nris;
11354 }
11355
11356 final List<NetworkRequest> requests = new ArrayList<>();
11357 // The NRI should be comprised of two layers:
11358 // - The request for the mobile network preferred.
11359 // - The request for the default network, for fallback.
11360 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011361 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011362 requests.add(createDefaultInternetRequestForTransport(
11363 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11364 final Set<UidRange> ranges = new ArraySet<>();
11365 for (final int uid : uids) {
11366 ranges.add(new UidRange(uid, uid));
11367 }
11368 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011369 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011370 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011371 return nris;
11372 }
11373
11374 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011375 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011376 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11377 addPerAppDefaultNetworkRequests(
11378 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011379 // Finally, rematch.
11380 rematchAllNetworksAndRequests();
11381 }
11382
Patrick Rohr2857ac42022-01-21 14:58:16 +010011383 private void handleIngressRateLimitChanged() {
11384 final long oldIngressRateLimit = mIngressRateLimit;
11385 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11386 mContext);
11387 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11388 if (canNetworkBeRateLimited(networkAgent)) {
11389 // If rate limit has previously been enabled, remove the old limit first.
11390 if (oldIngressRateLimit >= 0) {
11391 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11392 }
11393 if (mIngressRateLimit >= 0) {
11394 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11395 mIngressRateLimit);
11396 }
11397 }
11398 }
11399 }
11400
11401 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011402 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
11403 if (!SdkLevel.isAtLeastT()) return false;
11404
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011405 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11406 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11407 // internet connectivity can be rate limited.
11408 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11409 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011410 return false;
11411 }
11412
11413 final String iface = networkAgent.linkProperties.getInterfaceName();
11414 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011415 // This may happen in tests, but if there is no interface then there is nothing that
11416 // can be rate limited.
11417 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011418 return false;
11419 }
11420 return true;
11421 }
11422
James Mattis45d81842021-01-10 14:24:24 -080011423 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011424 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11425 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011426 }
11427
11428 /**
11429 * Used by automotive devices to set the network preferences used to direct traffic at an
11430 * application level as per the given OemNetworkPreferences. An example use-case would be an
11431 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11432 * vehicle via a particular network.
11433 *
11434 * Calling this will overwrite the existing preference.
11435 *
James Mattisda32cfe2021-01-26 16:23:52 -080011436 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011437 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011438 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011439 */
James Mattis47db0582021-01-01 14:13:35 -080011440 @Override
James Mattis45d81842021-01-10 14:24:24 -080011441 public void setOemNetworkPreference(
11442 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011443 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011444
James Mattisfa270db2021-05-31 17:11:10 -070011445 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11446 // Only bypass the permission/device checks if this is a valid test request.
11447 if (isValidTestOemNetworkPreference(preference)) {
11448 enforceManageTestNetworksPermission();
11449 } else {
11450 enforceAutomotiveDevice();
11451 enforceOemNetworkPreferencesPermission();
11452 validateOemNetworkPreferences(preference);
11453 }
James Mattis45d81842021-01-10 14:24:24 -080011454
James Mattis45d81842021-01-10 14:24:24 -080011455 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11456 new Pair<>(preference, listener)));
11457 }
11458
James Mattisfa270db2021-05-31 17:11:10 -070011459 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011460 * Sets the specified UIDs to get/receive the VPN as the only default network.
11461 *
11462 * Calling this will overwrite the existing network preference for this session, and the
11463 * specified UIDs won't get any default network when no VPN is connected.
11464 *
11465 * @param session The VPN session which manages the passed UIDs.
11466 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11467 * setting for this session if the array is empty. Null is not allowed, the
11468 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11469 * @hide
11470 */
11471 @Override
11472 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11473 Objects.requireNonNull(ranges);
11474 enforceNetworkStackOrSettingsPermission();
11475 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11476 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11477 throw new IllegalArgumentException(
11478 "setVpnNetworkPreference: Passed UID ranges overlap");
11479 }
11480
11481 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11482 new VpnNetworkPreferenceInfo(session,
11483 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11484 }
11485
11486 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11487 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11488
11489 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11490 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11491
11492 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11493 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11494 // Finally, rematch.
11495 rematchAllNetworksAndRequests();
11496 }
11497
11498 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11499 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11500 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11501 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11502 final List<NetworkRequest> requests = new ArrayList<>();
11503 // Request VPN only, so other networks won't be the fallback options when VPN is not
11504 // connected temporarily.
11505 requests.add(createVpnRequest());
11506 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11507 setNetworkRequestUids(requests, uidRanges);
11508 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11509 }
11510 return nris;
11511 }
11512
11513 /**
James Mattisfa270db2021-05-31 17:11:10 -070011514 * Check the validity of an OEM network preference to be used for testing purposes.
11515 * @param preference the preference to validate
11516 * @return true if this is a valid OEM network preference test request.
11517 */
11518 private boolean isValidTestOemNetworkPreference(
11519 @NonNull final OemNetworkPreferences preference) {
11520 // Allow for clearing of an existing OemNetworkPreference used for testing.
11521 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11522 // changes after this check is complete. This is an unlikely scenario as calling of this API
11523 // is controlled by the OEM therefore the added complexity is not worth adding given those
11524 // circumstances. That said, it is an edge case to be aware of hence this comment.
11525 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11526 && isTestOemNetworkPreference(mOemNetworkPreferences);
11527 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11528 }
11529
11530 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11531 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11532 return prefMap.size() == 1
11533 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11534 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11535 }
11536
James Mattis45d81842021-01-10 14:24:24 -080011537 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11538 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11539 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011540 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11541 throw new IllegalArgumentException(
11542 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11543 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011544 }
11545 }
11546 }
11547
11548 private void handleSetOemNetworkPreference(
11549 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011550 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011551 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11552 if (DBG) {
11553 log("set OEM network preferences :" + preference.toString());
11554 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011555
James Mattiscb1e0362021-04-06 17:07:42 -070011556 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011557 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11558 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11559 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011560 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011561
11562 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011563 try {
11564 listener.onComplete();
11565 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011566 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011567 }
James Mattis45d81842021-01-10 14:24:24 -080011568 }
11569 }
11570
paulhu74128522021-09-28 02:29:03 +000011571 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011572 // Skip the requests which are set by other network preference. Because the uid range rules
11573 // should stay in netd.
11574 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011575 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011576 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011577 }
11578
James Mattis3ce3d3c2021-02-09 18:18:28 -080011579 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11580 ensureRunningOnConnectivityServiceThread();
11581 mDefaultNetworkRequests.addAll(nris);
11582 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11583 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011584 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011585 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11586 nrisToRegister.addAll(
11587 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11588 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011589 }
11590
11591 /**
11592 * All current requests that are tracking the default network need to be assessed as to whether
11593 * or not the current set of per-application default requests will be changing their default
11594 * network. If so, those requests will need to be updated so that they will send callbacks for
11595 * default network changes at the appropriate time. Additionally, those requests tracking the
11596 * default that were previously updated by this flow will need to be reassessed.
11597 * @return the nris which will need to be updated.
11598 */
11599 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11600 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11601 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11602 // same nri in the map's values for each of its NetworkRequest objects.
11603 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011604 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011605 // Include this nri if it is currently being tracked.
11606 if (isPerAppTrackedNri(nri)) {
11607 defaultCallbackRequests.add(nri);
11608 continue;
11609 }
11610 // We only track callbacks for requests tracking the default.
11611 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11612 continue;
11613 }
11614 // Include this nri if it will be tracked by the new per-app default requests.
11615 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011616 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011617 if (isNriGoingToBeTracked) {
11618 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011619 }
11620 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011621 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011622 }
11623
James Mattis3ce3d3c2021-02-09 18:18:28 -080011624 /**
11625 * Create nris for those network requests that are currently tracking the default network that
11626 * are being controlled by a per-application default.
11627 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11628 * foundation when creating the nri. Important items include the calling uid's original
11629 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11630 * requests are assumed to have already been validated as needing to be updated.
11631 * @return the Set of nris to use when registering network requests.
11632 */
11633 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11634 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11635 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11636 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11637 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011638 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011639
Chalard Jean9473c982021-07-29 20:03:04 +090011640 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011641 if (trackingNri == mDefaultRequest) {
11642 callbackRequestsToRegister.add(new NetworkRequestInfo(
11643 callbackRequest,
11644 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11645 continue;
11646 }
11647
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011648 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011649 callbackRequestsToRegister.add(new NetworkRequestInfo(
11650 callbackRequest,
11651 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011652 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011653 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011654 }
11655 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011656 }
11657
Chalard Jean17215832021-03-01 14:06:28 +090011658 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11659 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011660 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011661 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011662 }
11663 }
11664
James Mattis45d81842021-01-10 14:24:24 -080011665 /**
11666 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11667 */
11668 @VisibleForTesting
11669 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011670 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011671 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011672 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011673 final SparseArray<Set<Integer>> uids =
11674 createUidsFromOemNetworkPreferences(preference);
11675 for (int i = 0; i < uids.size(); i++) {
11676 final int key = uids.keyAt(i);
11677 final Set<Integer> value = uids.valueAt(i);
11678 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11679 // No need to add an nri without any requests.
11680 if (0 == nri.mRequests.size()) {
11681 continue;
11682 }
11683 nris.add(nri);
11684 }
11685
11686 return nris;
11687 }
11688
11689 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11690 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011691 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011692 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011693 final List<UserHandle> users =
11694 mContext.getSystemService(UserManager.class).getUserHandles(true);
11695 if (null == users || users.size() == 0) {
11696 if (VDBG || DDBG) {
11697 log("No users currently available for setting the OEM network preference.");
11698 }
James Mattisb6b6a432021-06-01 22:30:36 -070011699 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011700 }
James Mattis45d81842021-01-10 14:24:24 -080011701 for (final Map.Entry<String, Integer> entry :
11702 preference.getNetworkPreferences().entrySet()) {
11703 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011704 // Add the rules for all users as this policy is device wide.
11705 for (final UserHandle user : users) {
11706 try {
11707 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11708 if (!prefToUids.contains(pref)) {
11709 prefToUids.put(pref, new ArraySet<>());
11710 }
11711 prefToUids.get(pref).add(uid);
11712 } catch (PackageManager.NameNotFoundException e) {
11713 // Although this may seem like an error scenario, it is ok that uninstalled
11714 // packages are sent on a network preference as the system will watch for
11715 // package installations associated with this network preference and update
11716 // accordingly. This is done to minimize race conditions on app install.
11717 continue;
James Mattis45d81842021-01-10 14:24:24 -080011718 }
James Mattis45d81842021-01-10 14:24:24 -080011719 }
11720 }
James Mattisb6b6a432021-06-01 22:30:36 -070011721 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011722 }
11723
11724 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11725 @OemNetworkPreferences.OemNetworkPreference final int preference,
11726 @NonNull final Set<Integer> uids) {
11727 final List<NetworkRequest> requests = new ArrayList<>();
11728 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11729 switch (preference) {
11730 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11731 requests.add(createUnmeteredNetworkRequest());
11732 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011733 requests.add(createDefaultInternetRequestForTransport(
11734 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011735 break;
11736 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11737 requests.add(createUnmeteredNetworkRequest());
11738 requests.add(createOemPaidNetworkRequest());
11739 break;
11740 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11741 requests.add(createOemPaidNetworkRequest());
11742 break;
11743 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11744 requests.add(createOemPrivateNetworkRequest());
11745 break;
James Mattisfa270db2021-05-31 17:11:10 -070011746 case OEM_NETWORK_PREFERENCE_TEST:
11747 requests.add(createUnmeteredNetworkRequest());
11748 requests.add(createTestNetworkRequest());
11749 requests.add(createDefaultRequest());
11750 break;
11751 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11752 requests.add(createTestNetworkRequest());
11753 break;
James Mattis45d81842021-01-10 14:24:24 -080011754 default:
11755 // This should never happen.
11756 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11757 + " called with invalid preference of " + preference);
11758 }
11759
James Mattisfa270db2021-05-31 17:11:10 -070011760 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011761 for (final int uid : uids) {
11762 ranges.add(new UidRange(uid, uid));
11763 }
11764 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011765 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011766 }
11767
11768 private NetworkRequest createUnmeteredNetworkRequest() {
11769 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11770 .addCapability(NET_CAPABILITY_NOT_METERED)
11771 .addCapability(NET_CAPABILITY_VALIDATED);
11772 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11773 }
11774
11775 private NetworkRequest createOemPaidNetworkRequest() {
11776 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11777 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11778 .addCapability(NET_CAPABILITY_OEM_PAID)
11779 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11780 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11781 }
11782
11783 private NetworkRequest createOemPrivateNetworkRequest() {
11784 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11785 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11786 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11787 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11788 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11789 }
11790
11791 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011792 final NetworkCapabilities netcap = new NetworkCapabilities();
11793 netcap.addCapability(NET_CAPABILITY_INTERNET);
11794 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11795 return netcap;
11796 }
11797
11798 private NetworkRequest createTestNetworkRequest() {
11799 final NetworkCapabilities netcap = new NetworkCapabilities();
11800 netcap.clearAll();
11801 netcap.addTransportType(TRANSPORT_TEST);
11802 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011803 }
James Mattis47db0582021-01-01 14:13:35 -080011804 }
markchien738ad912021-12-09 18:15:45 +080011805
11806 @Override
11807 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11808 enforceNetworkStackOrSettingsPermission();
11809
11810 try {
11811 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011812 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011813 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011814 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011815 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011816 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011817 throw new IllegalStateException(e);
11818 }
11819 }
11820
11821 @Override
11822 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11823 enforceNetworkStackOrSettingsPermission();
11824
11825 try {
11826 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011827 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011828 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011829 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011830 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011831 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011832 throw new IllegalStateException(e);
11833 }
11834 }
markchiene1561fa2021-12-09 22:00:56 +080011835
11836 @Override
markchien3c04e662022-03-22 16:29:56 +080011837 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011838 enforceNetworkStackOrSettingsPermission();
11839
markchien3c04e662022-03-22 16:29:56 +080011840 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11841 int firewallRule = getFirewallRuleType(chain, rule);
11842
11843 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11844 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11845 }
11846
markchiene1561fa2021-12-09 22:00:56 +080011847 try {
markchien3c04e662022-03-22 16:29:56 +080011848 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011849 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011850 throw new IllegalStateException(e);
11851 }
11852 }
markchien98a6f952022-01-13 23:43:53 +080011853
Motomu Utsumi900b8062023-01-19 16:16:49 +090011854 @Override
11855 public int getUidFirewallRule(final int chain, final int uid) {
11856 enforceNetworkStackOrSettingsPermission();
11857 return mBpfNetMaps.getUidRule(chain, uid);
11858 }
11859
markchien3c04e662022-03-22 16:29:56 +080011860 private int getFirewallRuleType(int chain, int rule) {
11861 final int defaultRule;
11862 switch (chain) {
11863 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011864 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11865 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011866 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011867 defaultRule = FIREWALL_RULE_ALLOW;
11868 break;
11869 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11870 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11871 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11872 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11873 defaultRule = FIREWALL_RULE_DENY;
11874 break;
11875 default:
11876 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11877 }
11878 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11879
11880 return rule;
11881 }
11882
markchien98a6f952022-01-13 23:43:53 +080011883 @Override
11884 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11885 enforceNetworkStackOrSettingsPermission();
11886
11887 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011888 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011889 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011890 throw new IllegalStateException(e);
11891 }
11892 }
11893
markchien00a0bed2022-01-13 23:46:13 +080011894 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011895 public boolean getFirewallChainEnabled(final int chain) {
11896 enforceNetworkStackOrSettingsPermission();
11897
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011898 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011899 }
11900
11901 @Override
markchien00a0bed2022-01-13 23:46:13 +080011902 public void replaceFirewallChain(final int chain, final int[] uids) {
11903 enforceNetworkStackOrSettingsPermission();
11904
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011905 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011906 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080011907
11908 @Override
11909 public IBinder getCompanionDeviceManagerProxyService() {
11910 enforceNetworkStackPermission(mContext);
11911 return mCdmps;
11912 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011913}