blob: 5f519711f3f9bb36f083f5cb98481d2dd7cf19ed [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,
914 // accessing this value requires holding a lock.
915 @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;
7004 try {
7005 synchronized (mSelfCertifiedCapabilityCache) {
7006 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7007 callerPackageName);
7008 if (applicationNetworkCapabilities == null) {
7009 final PackageManager packageManager = mContext.getPackageManager();
7010 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7011 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7012 callerPackageName
7013 );
7014 final XmlResourceParser parser = packageManager
7015 .getResourcesForApplication(callerPackageName)
7016 .getXml(networkSliceProperty.getResourceId());
7017 applicationNetworkCapabilities =
7018 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7019 mSelfCertifiedCapabilityCache.put(callerPackageName,
7020 applicationNetworkCapabilities);
7021 }
7022
7023 }
7024 } catch (PackageManager.NameNotFoundException ne) {
7025 throw new SecurityException(
7026 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7027 + " property");
7028 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7029 throw new SecurityException(e.getMessage());
7030 }
7031
7032 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7033 networkCapabilities);
7034 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007035 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007036 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007037 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7038 callingPackageName)) {
7039 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7040 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007041 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007042 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7043 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7044 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7045 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007046 }
junyulai96bd9fe2022-03-08 17:36:42 +08007047 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007048 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007049 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007050 }
7051 }
7052
fenglu3f357402015-03-20 11:29:56 -07007053 @Override
fenglub00f4882015-04-21 17:12:05 -07007054 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007055 enforceAccessPermission();
7056 NetworkAgentInfo nai = null;
7057 if (network == null) {
7058 return false;
7059 }
7060 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007061 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007062 }
7063 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007064 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007065 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007066 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007067 Integer uidReqs = mBandwidthRequests.get(uid);
7068 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007069 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007070 }
7071 mBandwidthRequests.put(uid, ++uidReqs);
7072 }
fenglu3f357402015-03-20 11:29:56 -07007073 return true;
7074 }
7075 return false;
7076 }
7077
Felipe Leme0a5ae422016-06-20 16:36:29 -07007078 private boolean isSystem(int uid) {
7079 return uid < Process.FIRST_APPLICATION_UID;
7080 }
fenglu3f357402015-03-20 11:29:56 -07007081
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007082 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007083 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007084 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007085 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007086 return;
7087 }
Hugo Benichi39621362017-02-11 17:04:43 +09007088 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7089 // Policy already enforced.
7090 return;
7091 }
paulhuaf50d7d2020-12-24 19:47:34 +08007092 final long ident = Binder.clearCallingIdentity();
7093 try {
7094 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7095 // If UID is restricted, don't allow them to bring up metered APNs.
7096 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7097 }
7098 } finally {
7099 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007100 }
7101 }
7102
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007103 @Override
7104 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007105 PendingIntent operation, @NonNull String callingPackageName,
7106 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007107 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007108 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007109 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007110 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007111 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007112 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007113 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007114 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007115 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007116 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7117 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007118
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007119 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007120 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007121 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7122 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007123 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007124 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7125 nri));
7126 return networkRequest;
7127 }
7128
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007129 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7130 mHandler.sendMessageDelayed(
7131 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007132 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007133 }
7134
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007135 @Override
7136 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007137 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007138 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007139 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007140 }
7141
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007142 // In order to implement the compatibility measure for pre-M apps that call
7143 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7144 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7145 // This ensures it has permission to do so.
7146 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7147 if (nc == null) {
7148 return false;
7149 }
7150 int[] transportTypes = nc.getTransportTypes();
7151 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7152 return false;
7153 }
7154 try {
7155 mContext.enforceCallingOrSelfPermission(
7156 android.Manifest.permission.ACCESS_WIFI_STATE,
7157 "ConnectivityService");
7158 } catch (SecurityException e) {
7159 return false;
7160 }
7161 return true;
7162 }
7163
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007164 @Override
7165 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007166 Messenger messenger, IBinder binder,
7167 @NetworkCallback.Flag int callbackFlags,
7168 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007169 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007170 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7171 enforceAccessPermission();
7172 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007173
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007174 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007175 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007176 Binder.getCallingPid(), callingUid, callingPackageName);
7177 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007178 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7179 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7180 // onLost and onAvailable callbacks when networks move in and out of the background.
7181 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7182 // can't request networks.
7183 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007184 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007185
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007186 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007187 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007188 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007189 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007190 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007191 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007192
7193 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7194 return networkRequest;
7195 }
7196
7197 @Override
7198 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007199 PendingIntent operation, @NonNull String callingPackageName,
7200 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007201 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007202 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007203 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7204 enforceAccessPermission();
7205 }
Chalard Jeandd421992021-12-16 23:16:02 +09007206 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007207 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007208 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007209 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007210 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007211
7212 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007213 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007214 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7215 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007216 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007217
WeiZhang1cc3f172021-06-03 19:02:04 -05007218 mHandler.sendMessage(mHandler.obtainMessage(
7219 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007220 }
7221
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007222 /** Returns the next Network provider ID. */
7223 public final int nextNetworkProviderId() {
7224 return mNextNetworkProviderId.getAndIncrement();
7225 }
7226
Erik Kline0c04b742016-07-07 16:50:58 +09007227 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007228 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007229 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007230 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007231 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007232 }
7233
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007234 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7235 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007236 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7237 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7238 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007239 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007240 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007241 return;
7242 }
7243
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007244 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7245 mNetworkProviderInfos.put(npi.messenger, npi);
7246 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007247 }
7248
7249 @Override
7250 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007251 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007252 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007253 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007254 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007255 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7256 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007257 }
7258
7259 @Override
7260 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007261 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007262 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007263 }
7264
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007265 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007266 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007267 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7268 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007269 Objects.requireNonNull(score);
7270 Objects.requireNonNull(caps);
7271 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007272 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007273 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007274 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7275 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007276 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7277 }
7278
Chalard Jeanbb902a52021-08-18 01:35:19 +09007279 private void updateOfferScore(final NetworkOffer offer) {
7280 final boolean yieldToBadWiFi =
7281 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7282 final NetworkOffer newOffer = new NetworkOffer(
7283 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7284 offer.caps, offer.callback, offer.providerId);
7285 if (offer.equals(newOffer)) return;
7286 handleRegisterNetworkOffer(newOffer);
7287 }
7288
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007289 @Override
7290 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007291 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007292 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7293 }
7294
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007295 private void handleUnregisterNetworkProvider(Messenger messenger) {
7296 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7297 if (npi == null) {
7298 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007299 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007300 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007301 // Unregister all the offers from this provider
7302 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7303 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007304 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007305 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7306 toRemove.add(noi);
7307 }
7308 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007309 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007310 handleUnregisterNetworkOffer(noi);
7311 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007312 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007313 }
7314
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007315 @Override
James Mattisf7027322020-12-13 16:28:14 -08007316 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007317 if (request.hasTransport(TRANSPORT_TEST)) {
7318 enforceNetworkFactoryOrTestNetworksPermission();
7319 } else {
7320 enforceNetworkFactoryPermission();
7321 }
James Mattisf7027322020-12-13 16:28:14 -08007322 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7323 if (nri != null) {
7324 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7325 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7326 mHandler.post(() -> handleReleaseNetworkRequest(
7327 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7328 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007329 }
7330
Paul Jensen1f567382015-02-13 14:18:39 -05007331 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7332 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007333 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007334 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007335 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007336 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007337 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007338
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007339 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007340 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007341 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007342
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007343 // UID ranges for users that are currently blocked by VPNs.
7344 // This array is accessed and iterated on multiple threads without holding locks, so its
7345 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7346 // (on the handler thread).
7347 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7348
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007349 // Must only be accessed on the handler thread
7350 @NonNull
7351 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7352
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007353 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007354 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007355
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007356 // Current OEM network preferences. This object must only be written to on the handler thread.
7357 // Since it is immutable and always non-null, other threads may read it if they only care
7358 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007359 @NonNull
7360 private OemNetworkPreferences mOemNetworkPreferences =
7361 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007362 // Current per-profile network preferences. This object follows the same threading rules as
7363 // the OEM network preferences above.
7364 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007365 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7366 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007367
lucaslin3ba7cc22022-12-19 02:35:33 +00007368 // Current VPN network preferences. This object follows the same threading rules as the OEM
7369 // network preferences above.
7370 @NonNull
7371 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7372 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7373
paulhu51f77dc2021-06-07 02:34:20 +00007374 // A set of UIDs that should use mobile data preferentially if available. This object follows
7375 // the same threading rules as the OEM network preferences above.
7376 @NonNull
7377 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7378
James Mattiscb1e0362021-04-06 17:07:42 -07007379 // OemNetworkPreferences activity String log entries.
7380 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7381 @NonNull
7382 private final LocalLog mOemNetworkPreferencesLogs =
7383 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7384
James Mattis02220e22021-03-13 19:27:21 -08007385 /**
7386 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7387 * @param packageName the package name to check existence of a mapping for.
7388 * @return true if a mapping exists, false otherwise
7389 */
7390 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7391 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7392 }
7393
James Mattise3ef1912020-12-20 11:09:58 -08007394 // The always-on request for an Internet-capable network that apps without a specific default
7395 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007396 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007397 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007398 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007399 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007400 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007401 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007402 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007403
James Mattisd31bdfa2020-12-23 16:37:26 -08007404 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7405 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7406 }
7407
7408 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007409 * Return the default network request currently tracking the given uid.
7410 * @param uid the uid to check.
7411 * @return the NetworkRequestInfo tracking the given uid.
7412 */
7413 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007414 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007415 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007416 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007417 // Checking the first request is sufficient as only multilayer requests will have more
7418 // than one request and for multilayer, all requests will track the same uids.
7419 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007420 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007421 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007422 highestPriorityNri = nri;
7423 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007424 }
7425 }
paulhuaa0743d2021-05-26 21:56:03 +08007426 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007427 }
7428
7429 /**
7430 * Get a copy of the network requests of the default request that is currently tracking the
7431 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007432 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7433 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007434 * @param requestorUid the uid to check the default for.
7435 * @param requestorPackageName the requestor's package name.
7436 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7437 */
7438 @NonNull
7439 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007440 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007441 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007442 getDefaultRequestTrackingUid(asUid).mRequests,
7443 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007444 }
7445
7446 /**
7447 * Copy the given nri's NetworkRequest collection.
7448 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007449 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7450 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007451 * @param requestorUid the uid to set on the copied collection.
7452 * @param requestorPackageName the package name to set on the copied collection.
7453 * @return the copied NetworkRequest collection.
7454 */
7455 @NonNull
7456 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007457 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7458 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007459 final List<NetworkRequest> requests = new ArrayList<>();
7460 for (final NetworkRequest nr : requestsToCopy) {
7461 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007462 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007463 nr.legacyType, nextNetworkRequestId(), nr.type));
7464 }
7465 return requests;
7466 }
7467
7468 @NonNull
7469 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007470 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7471 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007472 // These capabilities are for a TRACK_DEFAULT callback, so:
7473 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7474 // mDefaultRequest and a per-UID default request.
7475 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007476 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007477 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007478 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7479 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007480 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007481 restrictRequestUidsForCallerAndSetRequestorInfo(
7482 netCap, requestorUid, requestorPackageName);
7483 return netCap;
7484 }
7485
7486 /**
7487 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7488 * @param nr the network request to check for equality against.
7489 * @return the nri if one exists, null otherwise.
7490 */
7491 @Nullable
7492 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7493 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7494 if (nri.getNetworkRequestForCallback().equals(nr)) {
7495 return nri;
7496 }
7497 }
7498 return null;
7499 }
7500
7501 /**
7502 * Check if an nri is currently being managed by per-app default networking.
7503 * @param nri the nri to check.
7504 * @return true if this nri is currently being managed by per-app default networking.
7505 */
7506 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7507 // nri.mRequests.get(0) is only different from the original request filed in
7508 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7509 // functionality therefore if these two don't match, it means this particular nri is
7510 // currently being managed by a per-app default.
7511 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7512 }
7513
7514 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007515 * Determine if an nri is a managed default request that disallows default networking.
7516 * @param nri the request to evaluate
7517 * @return true if device-default networking is disallowed
7518 */
7519 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7520 // Check if this nri is a managed default that supports the default network at its
7521 // lowest priority request.
7522 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7523 final NetworkCapabilities lowestPriorityNetCap =
7524 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7525 return isPerAppDefaultRequest(nri)
7526 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7527 lowestPriorityNetCap));
7528 }
7529
Erik Kline05f2b402015-04-30 12:58:40 +09007530 // Request used to optionally keep mobile data active even when higher
7531 // priority networks like Wi-Fi are active.
7532 private final NetworkRequest mDefaultMobileDataRequest;
7533
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007534 // Request used to optionally keep wifi data active even when higher
7535 // priority networks like ethernet are active.
7536 private final NetworkRequest mDefaultWifiRequest;
7537
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007538 // Request used to optionally keep vehicle internal network always active
7539 private final NetworkRequest mDefaultVehicleRequest;
7540
James Mattisd31bdfa2020-12-23 16:37:26 -08007541 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7542 // network with no service. This NAI should never be matched against, nor should any public API
7543 // ever return the associated network. For this reason, this NAI is not in the list of available
7544 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7545 // default requests that don't support using the device default network which will ultimately
7546 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7547 @VisibleForTesting
7548 final NetworkAgentInfo mNoServiceNetwork;
7549
Chalard Jean5b409c72021-02-04 13:12:59 +09007550 // The NetworkAgentInfo currently satisfying the default request, if any.
7551 private NetworkAgentInfo getDefaultNetwork() {
7552 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007553 }
7554
James Mattis2516da32021-01-31 17:06:19 -08007555 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007556 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007557 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7558 // Currently, all network requests will have the same uids therefore checking the first
7559 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007560 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007561 if (null == uids) {
7562 continue;
7563 }
7564 for (final UidRange range : uids) {
7565 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007566 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007567 highestPriorityNri = nri;
7568 }
James Mattis2516da32021-01-31 17:06:19 -08007569 }
7570 }
7571 }
paulhuaa0743d2021-05-26 21:56:03 +08007572 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007573 }
7574
Varun Ananddf569952019-02-06 10:13:38 -08007575 @Nullable
7576 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7577 return nai != null ? nai.network : null;
7578 }
7579
7580 private void ensureRunningOnConnectivityServiceThread() {
7581 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7582 throw new IllegalStateException(
7583 "Not running on ConnectivityService thread: "
7584 + Thread.currentThread().getName());
7585 }
7586 }
7587
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007588 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007589 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7590 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007591 }
7592
Chalard Jean29d06db2018-05-02 21:14:54 +09007593 /**
7594 * Register a new agent with ConnectivityService to handle a network.
7595 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007596 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007597 * @param networkInfo the initial info associated with this network. It can be updated later :
7598 * see {@link #updateNetworkInfo}.
7599 * @param linkProperties the initial link properties of this network. They can be updated
7600 * later : see {@link #updateLinkProperties}.
7601 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007602 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007603 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007604 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007605 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007606 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007607 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007608 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007609 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007610 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7611 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007612 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7613 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7614 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007615 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007616 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007617 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007618 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007619 } else {
7620 enforceNetworkFactoryPermission();
7621 }
7622
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007623 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007624 final long token = Binder.clearCallingIdentity();
7625 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007626 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007627 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007628 } finally {
7629 Binder.restoreCallingIdentity(token);
7630 }
7631 }
7632
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007633 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007634 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007635 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7636 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007637
Chalard Jeandbc46952022-02-02 00:14:18 +09007638 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7639 // and mutate them at any time.
7640 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7641 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7642 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7643
Chalard Jean366c5252022-01-25 18:27:53 +09007644 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007645 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007646 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7647 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007648 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007649 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007650 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007651 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7652 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007653
Chalard Jeandbc46952022-02-02 00:14:18 +09007654 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007655 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007656 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007657 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007658 mDeps.getNetworkStack().makeNetworkMonitor(
7659 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007660 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7661 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007662 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007663 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007664 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007665 }
7666
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007667 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007668 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007669 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007670 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007671 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007672 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7673 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7674 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007675
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007676 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007677
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007678 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007679 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007680 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007681 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007682
7683 try {
7684 networkMonitor.start();
7685 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007686 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007687 }
Chalard Jean366c5252022-01-25 18:27:53 +09007688
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007689 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007690 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007691 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007692 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007693 }
7694
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007695 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7696 @NonNull public final NetworkOffer offer;
7697
7698 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7699 this.offer = offer;
7700 }
7701
7702 @Override
7703 public void binderDied() {
7704 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7705 }
7706 }
7707
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007708 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7709 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7710 if (npi.providerId == providerId) return true;
7711 }
7712 return false;
7713 }
7714
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007715 /**
7716 * Register or update a network offer.
7717 * @param newOffer The new offer. If the callback member is the same as an existing
7718 * offer, it is an update of that offer.
7719 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007720 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007721 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7722 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007723 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007724 // This may actually happen if a provider updates its score or registers and then
7725 // immediately unregisters. The offer would still be in the handler queue, but the
7726 // provider would have been removed.
7727 if (DBG) log("Received offer from an unregistered provider");
7728 return;
7729 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007730 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7731 if (null != existingOffer) {
7732 handleUnregisterNetworkOffer(existingOffer);
7733 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007734 if (DBG) {
7735 // handleUnregisterNetworkOffer has already logged the old offer
7736 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7737 }
7738 } else {
7739 if (DBG) {
7740 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7741 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007742 }
7743 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7744 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007745 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007746 } catch (RemoteException e) {
7747 noi.binderDied();
7748 return;
7749 }
7750 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007751 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007752 }
7753
7754 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7755 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007756 if (DBG) {
7757 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7758 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007759
7760 // If the provider removes the offer and dies immediately afterwards this
7761 // function may be called twice in a row, but the array will no longer contain
7762 // the offer.
7763 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007764 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007765 }
7766
7767 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7768 @NonNull final INetworkOfferCallback callback) {
7769 ensureRunningOnConnectivityServiceThread();
7770 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007771 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007772 }
7773 return null;
7774 }
7775
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007776 /**
7777 * Called when receiving LinkProperties directly from a NetworkAgent.
7778 * Stores into |nai| any data coming from the agent that might also be written to the network's
7779 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7780 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007781 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007782 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007783 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7784 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007785 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007786 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007787 }
7788
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007789 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007790 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007791 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007792
Lorenzo Colittid523d142020-04-01 20:16:30 +09007793 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7794 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7795 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007796 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007797
Suprabh Shukla1e312032023-01-24 03:36:37 -08007798 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007799
7800 // update filtering rules, need to happen after the interface update so netd knows about the
7801 // new interface (the interface name -> index map becomes initialized)
7802 updateVpnFiltering(newLp, oldLp, networkAgent);
7803
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007804 updateMtu(newLp, oldLp);
7805 // TODO - figure out what to do for clat
7806// for (LinkProperties lp : newLp.getStackedLinks()) {
7807// updateMtu(lp, null);
7808// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007809 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007810 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7811 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007812
Erik Klineb9888902016-04-05 13:30:49 +09007813 updateRoutes(newLp, oldLp, netId);
7814 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007815 // Make sure LinkProperties represents the latest private DNS status.
7816 // This does not need to be done before updateDnses because the
7817 // LinkProperties are not the source of the private DNS configuration.
7818 // updateDnses will fetch the private DNS configuration from DnsManager.
7819 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007820
Chalard Jean5b409c72021-02-04 13:12:59 +09007821 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007822 handleApplyDefaultProxy(newLp.getHttpProxy());
7823 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007824 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007825 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007826
7827 updateWakeOnLan(newLp);
7828
Hai Shalome58bdc62021-01-11 18:45:34 -08007829 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7830 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7831 // does, it needs to be merged here.
7832 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7833 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007834
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007835 // TODO - move this check to cover the whole function
7836 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007837 synchronized (networkAgent) {
7838 networkAgent.linkProperties = newLp;
7839 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007840 // Start or stop DNS64 detection and 464xlat according to network state.
7841 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007842 // Notify NSS when relevant events happened. Currently, NSS only cares about
7843 // interface changed to update clat interfaces accounting.
7844 final boolean interfacesChanged = oldLp == null
7845 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7846 if (interfacesChanged) {
7847 notifyIfacesChangedForNetworkStats();
7848 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007849 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7850 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007851 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007852 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007853
7854 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007855 }
7856
Hai Shalome58bdc62021-01-11 18:45:34 -08007857 /**
7858 * @param naData captive portal data from NetworkAgent
7859 * @param apiData captive portal data from capport API
7860 */
7861 @Nullable
7862 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7863 CaptivePortalData apiData) {
7864 if (naData == null || apiData == null) {
7865 return naData == null ? apiData : naData;
7866 }
7867 final CaptivePortalData.Builder captivePortalBuilder =
7868 new CaptivePortalData.Builder(naData);
7869
7870 if (apiData.isCaptive()) {
7871 captivePortalBuilder.setCaptive(true);
7872 }
7873 if (apiData.isSessionExtendable()) {
7874 captivePortalBuilder.setSessionExtendable(true);
7875 }
7876 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7877 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7878 // otherwise data would be inconsistent. Prefer the capport API info if present,
7879 // as it can generally be refreshed more often.
7880 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7881 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7882 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7883 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7884 // No source has time / bytes remaining information: surface the newest refresh time
7885 // for other fields
7886 captivePortalBuilder.setRefreshTime(
7887 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7888 }
7889
Hai Shalom7c6ab402021-02-04 19:34:06 -08007890 // Prioritize the user portal URL from the network agent if the source is authenticated.
7891 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7892 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7893 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7894 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007895 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007896 // Prioritize the venue information URL from the network agent if the source is
7897 // authenticated.
7898 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7899 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7900 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7901 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007902 }
7903 return captivePortalBuilder.build();
7904 }
7905
Suprabh Shukla1e312032023-01-24 03:36:37 -08007906 private String makeNflogPrefix(String iface, long networkHandle) {
7907 // This needs to be kept in sync and backwards compatible with the decoding logic in
7908 // NetdEventListenerService, which is non-mainline code.
7909 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
7910 }
7911
7912 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007913 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007914 // marks on unsupported interfaces is harmless.
Suprabh Shukla1e312032023-01-24 03:36:37 -08007915 if (!nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007916 return;
7917 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007918
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007919 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7920 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7921
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007922 // Mask/mark of zero will not detect anything interesting.
7923 // Don't install rules unless both values are nonzero.
7924 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007925 return;
7926 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007927
Suprabh Shukla1e312032023-01-24 03:36:37 -08007928 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007929 try {
7930 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007931 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007932 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007933 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007934 }
7935 } catch (Exception e) {
7936 loge("Exception modifying wakeup packet monitoring: " + e);
7937 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007938 }
7939
Junyu Lai970963e2022-10-25 15:46:47 +08007940 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09007941 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08007942 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09007943 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08007944 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09007945 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007946 for (final String iface : interfaceDiff.added) {
7947 try {
7948 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007949 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08007950 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007951 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08007952 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007953 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007954 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007955 }
Paul Jensenbff73492014-04-28 10:33:11 -04007956 }
7957 }
Chalard Jean9589e722019-11-19 19:03:53 +09007958 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007959 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007960 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08007961 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007962 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007963 } catch (Exception e) {
7964 loge("Exception removing interface: " + e);
7965 }
7966 }
7967 }
7968
Tyler Weare4314862019-12-05 14:55:30 -08007969 // TODO: move to frameworks/libs/net.
7970 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7971 final String nextHop;
7972
7973 switch (route.getType()) {
7974 case RouteInfo.RTN_UNICAST:
7975 if (route.hasGateway()) {
7976 nextHop = route.getGateway().getHostAddress();
7977 } else {
7978 nextHop = INetd.NEXTHOP_NONE;
7979 }
7980 break;
7981 case RouteInfo.RTN_UNREACHABLE:
7982 nextHop = INetd.NEXTHOP_UNREACHABLE;
7983 break;
7984 case RouteInfo.RTN_THROW:
7985 nextHop = INetd.NEXTHOP_THROW;
7986 break;
7987 default:
7988 nextHop = INetd.NEXTHOP_NONE;
7989 break;
7990 }
7991
7992 final RouteInfoParcel rip = new RouteInfoParcel();
7993 rip.ifName = route.getInterface();
7994 rip.destination = route.getDestination().toString();
7995 rip.nextHop = nextHop;
7996 rip.mtu = route.getMtu();
7997
7998 return rip;
7999 }
8000
Paul Jensene0fd4a82014-08-06 15:51:33 -04008001 /**
8002 * Have netd update routes from oldLp to newLp.
8003 * @return true if routes changed between oldLp and newLp
8004 */
Junyu Lai970963e2022-10-25 15:46:47 +08008005 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8006 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008007 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008008 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8009 new CompareOrUpdateResult<>(
8010 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008011 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008012 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008013
8014 // add routes before removing old in case it helps with continuous connectivity
8015
Chalard Jean9dd11612018-06-04 16:52:49 +09008016 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008017 for (RouteInfo route : routeDiff.added) {
8018 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008019 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008020 try {
Tyler Weare4314862019-12-05 14:55:30 -08008021 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008022 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008023 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008024 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008025 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008026 }
8027 }
8028 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008029 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008030 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008031 try {
Tyler Weare4314862019-12-05 14:55:30 -08008032 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008033 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008034 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008035 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008036 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008037 }
8038 }
8039
8040 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008041 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008042 try {
Tyler Weare4314862019-12-05 14:55:30 -08008043 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008044 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008045 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008046 }
8047 }
Tyler Weare4314862019-12-05 14:55:30 -08008048
8049 for (RouteInfo route : routeDiff.updated) {
8050 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8051 try {
8052 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8053 } catch (Exception e) {
8054 loge("Exception in networkUpdateRouteParcel: " + e);
8055 }
8056 }
8057 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8058 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008059 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008060
Junyu Lai970963e2022-10-25 15:46:47 +08008061 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8062 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008063 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8064 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008065 }
Erik Klineb9888902016-04-05 13:30:49 +09008066
Erik Kline31b4a9e2018-01-11 21:07:29 +09008067 if (DBG) {
8068 final Collection<InetAddress> dnses = newLp.getDnsServers();
8069 log("Setting DNS servers for network " + netId + " to " + dnses);
8070 }
Erik Klineb9888902016-04-05 13:30:49 +09008071 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008072 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008073 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008074 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008075 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008076 }
Erik Kline54e35c02017-04-07 15:29:29 +09008077 }
8078
Junyu Lai970963e2022-10-25 15:46:47 +08008079 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8080 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008081 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8082 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008083 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8084 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008085
8086 if (!wasFiltering && !needsFiltering) {
8087 // Nothing to do.
8088 return;
8089 }
8090
8091 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8092 // Nothing changed.
8093 return;
8094 }
8095
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008096 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008097 if (ranges == null || ranges.isEmpty()) {
8098 return;
8099 }
8100
Qingxi Libb8da982020-01-17 17:54:27 -08008101 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008102 // TODO: this create a window of opportunity for apps to receive traffic between the time
8103 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008104 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008105 // old rules are being removed.
8106 if (wasFiltering) {
8107 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8108 }
8109 if (needsFiltering) {
8110 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8111 }
8112 }
8113
Valentin Iftime9fa35092019-09-24 13:32:13 +02008114 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008115 if (mWolSupportedInterfaces == null) {
8116 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008117 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008118 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008119 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8120 }
8121
Luke Huangb913c812018-08-24 20:33:16 +08008122 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008123 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008124 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008125 }
8126 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008127 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008128 }
Luke Huangb913c812018-08-24 20:33:16 +08008129 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008130 }
8131
Chalard Jean62edfd82019-12-02 18:39:29 +09008132 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8133 @NonNull final NetworkCapabilities newNc) {
8134 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8135 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008136 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008137 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008138 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008139 } catch (RemoteException | ServiceSpecificException e) {
8140 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008141 }
8142 }
8143 }
8144
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008145 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008146 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008147 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008148 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008149 underlyingNetworks = underlyingNetworksOrDefault(
8150 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008151 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008152 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8153 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008154 // metered if any underlying is metered, or originally declared metered by the agent.
8155 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008156 boolean roaming = false; // roaming if any underlying is roaming
8157 boolean congested = false; // congested if any underlying is congested
8158 boolean suspended = true; // suspended if all underlying are suspended
8159
8160 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008161 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008162 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008163 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008164 for (Network underlyingNetwork : underlyingNetworks) {
8165 final NetworkAgentInfo underlying =
8166 getNetworkAgentInfoForNetwork(underlyingNetwork);
8167 if (underlying == null) continue;
8168
8169 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8170 hadUnderlyingNetworks = true;
8171 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008172 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008173 }
8174
8175 // Merge capabilities of this underlying network. For bandwidth, assume the
8176 // worst case.
8177 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8178 underlyingCaps.getLinkDownstreamBandwidthKbps());
8179 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8180 underlyingCaps.getLinkUpstreamBandwidthKbps());
8181 // If this underlying network is metered, the VPN is metered (it may cost money
8182 // to send packets on this network).
8183 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8184 // If this underlying network is roaming, the VPN is roaming (the billing structure
8185 // is different than the usual, local one).
8186 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8187 // If this underlying network is congested, the VPN is congested (the current
8188 // condition of the network affects the performance of this network).
8189 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8190 // If this network is not suspended, the VPN is not suspended (the VPN
8191 // is able to transfer some data).
8192 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008193 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008194 }
8195 }
8196 if (!hadUnderlyingNetworks) {
8197 // No idea what the underlying networks are; assume reasonable defaults
8198 metered = true;
8199 roaming = false;
8200 congested = false;
8201 suspended = false;
8202 }
8203
Chalard Jean1d420b32022-10-12 16:39:37 +09008204 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008205 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8206 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8207 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8208 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8209 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8210 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008211 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008212 }
8213
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008214 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008215 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8216 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8217 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008218 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008219 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008220 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008221 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008222 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8223 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008224 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008225 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008226 if (nai.everConnected()
8227 && !nai.isVPN()
8228 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008229 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008230 // does not cause any request (that is not a listen) currently matching that agent to
8231 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008232 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008233 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008234 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008235 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008236 }
8237
Paul Jensen53f08952015-06-16 14:27:36 -04008238 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008239 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008240 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008241 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008242 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008243 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008244 }
Chalard Jean254bd162022-08-25 13:04:51 +09008245 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008246 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008247 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008248 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008249 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008250 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008251 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008252 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008253 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008254 }
Chalard Jean254bd162022-08-25 13:04:51 +09008255 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008256 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8257 } else {
8258 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8259 }
lucasline117e2e2019-10-22 18:27:33 +08008260 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008261
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008262 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008263 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8264 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008265 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008266 }
8267
Lorenzo Colittibd079452021-07-02 11:47:57 +09008268 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008269 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008270 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008271 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008272 }
8273
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008274 return newNc;
8275 }
8276
Lorenzo Colitti44840702021-01-11 22:27:57 +09008277 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8278 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8279 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8280 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8281 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8282 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8283 if (prevSuspended != suspended) {
8284 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8285 // onResumed have been removed.
8286 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8287 : ConnectivityManager.CALLBACK_RESUMED);
8288 }
8289 if (prevSuspended != suspended || prevRoaming != roaming) {
8290 // updateNetworkInfo will mix in the suspended info from the capabilities and
8291 // take appropriate action for the network having possibly changed state.
8292 updateNetworkInfo(nai, nai.networkInfo);
8293 }
8294 }
8295
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008296 /**
8297 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8298 *
8299 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8300 * capabilities we manage and store in {@code nai}, such as validated status and captive
8301 * portal status)
8302 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8303 * potentially triggers rematches.
8304 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8305 * change.)
8306 *
8307 * @param oldScore score of the network before any of the changes that prompted us
8308 * to call this function.
8309 * @param nai the network having its capabilities updated.
8310 * @param nc the new network capabilities.
8311 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008312 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008313 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008314 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008315 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008316 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8317 if (null != differences) {
8318 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8319 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008320 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008321 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008322
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008323 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008324 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008325 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008326
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008327 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008328 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8329 // the change we're processing can't affect any requests, it can only affect the listens
8330 // on this network. We might have been called by rematchNetworkAndRequests when a
8331 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008332 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008333 } else {
8334 // If the requestable capabilities have changed or the score changed, we can't have been
8335 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008336 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008337 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008338 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008339 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008340
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008341 final boolean oldMetered = prevNc.isMetered();
8342 final boolean newMetered = newNc.isMetered();
8343 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008344
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008345 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008346 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8347 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008348 }
junyulaif2c67e42018-08-07 19:50:45 +08008349
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008350 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8351 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008352
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008353 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008354 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008355 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008356 }
8357
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008358 // This network might have been underlying another network. Propagate its capabilities.
8359 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008360
8361 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008362 mDnsManager.updateTransportsForNetwork(
8363 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008364 }
lucaslin53e8a262021-06-08 01:43:59 +08008365
8366 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008367 }
8368
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008369 /** Convenience method to update the capabilities for a given network. */
8370 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008371 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008372 }
8373
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008374 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008375 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008376 *
8377 * Ingress interface filtering enforces that all apps under the given network can only receive
8378 * packets from the network's interface (and loopback). This is important for VPNs because
8379 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8380 * non-VPN interfaces.
8381 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008382 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008383 * 1. the network is an app VPN (not legacy VPN)
8384 * 2. the VPN does not allow bypass
8385 * 3. the VPN is fully-routed
8386 * 4. the VPN interface is non-null
8387 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008388 * @see INetd#firewallAddUidInterfaceRules
8389 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008390 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008391 @Nullable
8392 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008393 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008394 if (nc == null || lp == null) return null;
8395 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008396 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008397 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008398 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008399 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008400 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008401 && !lp.hasExcludeRoute()) {
8402 return lp.getInterfaceName();
8403 }
8404 return null;
8405 }
8406
8407 /**
8408 * Returns whether we need to set interface filtering rule or not
8409 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008410 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008411 String isolationIface) {
8412 // Allow rules are always needed if VPN isolation is enabled.
8413 if (isolationIface != null) return true;
8414
8415 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8416 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8417 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8418 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008419 }
8420
Chiachang Wang28afaff2020-12-10 22:24:47 +08008421 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8422 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8423 int index = 0;
8424 for (UidRange range : ranges) {
8425 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8426 index++;
8427 }
8428 return stableRanges;
8429 }
8430
Chalard Jeane6c95272022-01-25 21:04:21 +09008431 private static UidRangeParcel[] intsToUidRangeStableParcels(
8432 final @NonNull ArraySet<Integer> uids) {
8433 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8434 int index = 0;
8435 for (int uid : uids) {
8436 stableRanges[index] = new UidRangeParcel(uid, uid);
8437 index++;
8438 }
8439 return stableRanges;
8440 }
8441
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008442 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8443 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8444 for (int i = 0; i < ranges.length; i++) {
8445 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8446 }
8447 return stableRanges;
8448 }
8449
Ken Chen5e65a852020-12-24 12:59:10 +08008450 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8451 int[] exemptUids) {
8452 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8453 try {
8454 mNetd.socketDestroy(ranges, exemptUids);
8455 } catch (Exception e) {
8456 loge("Exception in socket destroy: ", e);
8457 }
8458 }
8459 }
8460
paulhuaa0743d2021-05-26 21:56:03 +08008461 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008462 int[] exemptUids = new int[2];
8463 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8464 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8465 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8466 exemptUids[0] = VPN_UID;
8467 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8468 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8469
8470 maybeCloseSockets(nai, ranges, exemptUids);
8471 try {
8472 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008473 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008474 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008475 } else {
paulhu0e79d952021-06-09 16:11:35 +08008476 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008477 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008478 }
8479 } catch (Exception e) {
8480 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8481 " on netId " + nai.network.netId + ". " + e);
8482 }
8483 maybeCloseSockets(nai, ranges, exemptUids);
8484 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008485
lucaslin53e8a262021-06-08 01:43:59 +08008486 private boolean isProxySetOnAnyDefaultNetwork() {
8487 ensureRunningOnConnectivityServiceThread();
8488 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8489 final NetworkAgentInfo nai = nri.getSatisfier();
8490 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8491 return true;
8492 }
8493 }
8494 return false;
8495 }
8496
8497 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8498 NetworkCapabilities newNc) {
8499 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8500 // the proxy might be changed since the default network satisfied by the apps might also
8501 // changed.
8502 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8503 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008504 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8505 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008506 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008507 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8508 mProxyTracker.sendProxyBroadcast();
8509 }
8510 }
8511
Chalard Jeane6c95272022-01-25 21:04:21 +09008512 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8513 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008514 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8515 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008516 if (null == prevRanges) prevRanges = new ArraySet<>();
8517 if (null == newRanges) newRanges = new ArraySet<>();
8518 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8519
8520 prevRanges.removeAll(newRanges);
8521 newRanges.removeAll(prevRangesCopy);
8522
8523 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008524 // When updating the VPN uid routing rules, add the new range first then remove the old
8525 // range. If old range were removed first, there would be a window between the old
8526 // range being removed and the new range being added, during which UIDs contained
8527 // in both ranges are not subject to any VPN routing rules. Adding new range before
8528 // removing old range works because, unlike the filtering rules below, it's possible to
8529 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008530 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8531 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8532 // [1-5] & [1-2],[4-5] == [3]
8533 // Then we can do:
8534 // maybeCloseSockets([3])
8535 // mNetd.networkAddUidRanges([1-2],[4-5])
8536 // mNetd.networkRemoveUidRanges([1-5])
8537 // maybeCloseSockets([3])
8538 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8539 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008540 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008541 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008542 }
8543 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008544 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008545 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008546 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8547 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008548 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8549 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008550 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008551 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008552 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8553 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8554 // were added first and then newRanges got removed later, there would be only one uid
8555 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8556 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8557 // Note that this is in contrast with the (more robust) update of VPN routing rules
8558 // above, where the addition of new ranges happens before the removal of old ranges.
8559 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8560 // to be removed will never overlap with the new range to be added.
8561 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008562 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8563 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008564 }
8565 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008566 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008567 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008568 } catch (Exception e) {
8569 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008570 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008571 }
8572 }
8573
Chalard Jeande665262022-02-25 16:12:12 +09008574 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008575 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8576 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008577 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8578 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008579 if (prevEmpty && newEmpty) return;
8580
8581 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008582 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008583 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008584 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008585
8586 if (prevUids.equals(newUids)) return;
8587
8588 // This implementation is very simple and vastly faster for sets of Integers than
8589 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8590 // a key computed from the value and has storage for that.
8591 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8592 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8593 toRemove.removeAll(newUids);
8594 toAdd.removeAll(prevUids);
8595
8596 try {
8597 if (!toAdd.isEmpty()) {
8598 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8599 nai.network.netId,
8600 intsToUidRangeStableParcels(toAdd),
8601 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8602 }
8603 if (!toRemove.isEmpty()) {
8604 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8605 nai.network.netId,
8606 intsToUidRangeStableParcels(toRemove),
8607 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8608 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008609 } catch (ServiceSpecificException e) {
8610 // Has the interface disappeared since the network was built ?
8611 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008612 } catch (RemoteException e) {
8613 // Netd died. This usually causes a runtime restart anyway.
8614 }
8615 }
8616
Junyu Lai2ed7d412022-10-07 16:52:21 +08008617 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8618 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008619 ensureRunningOnConnectivityServiceThread();
8620
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008621 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008622 // Ignore updates for disconnected networks
8623 return;
8624 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008625 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008626 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008627 + "; created=" + nai.getCreatedTime()
8628 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008629 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008630 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8631 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008632 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008633 }
8634
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008635 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8636 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008637 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008638 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008639 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008640 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8641 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8642 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008643 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8644 // need to be sent as a separate extra.
8645 final NetworkRequest req = nri.isMultilayerRequest()
8646 ? nri.getActiveRequest()
8647 // Non-multilayer listen requests do not have an active request
8648 : nri.mRequests.get(0);
8649 if (req == null) {
8650 Log.wtf(TAG, "No request in NRI " + nri);
8651 }
8652 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008653 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008654 sendIntent(nri.mPendingIntent, intent);
8655 }
8656 // else not handled
8657 }
8658
Michael Groover73f69482023-01-27 11:01:25 -06008659 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
8660 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008661 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8662 mPendingIntentWakeLock.acquire();
8663 try {
8664 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008665 final BroadcastOptions options = BroadcastOptions.makeBasic();
8666 if (SdkLevel.isAtLeastT()) {
8667 // Explicitly disallow the receiver from starting activities, to prevent apps from
8668 // utilizing the PendingIntent as a backdoor to do this.
8669 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8670 }
8671 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8672 null /* requiredPermission */,
8673 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008674 } catch (PendingIntent.CanceledException e) {
8675 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8676 mPendingIntentWakeLock.release();
8677 releasePendingNetworkRequest(pendingIntent);
8678 }
8679 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8680 }
8681
8682 @Override
8683 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8684 String resultData, Bundle resultExtras) {
8685 if (DBG) log("Finished sending " + pendingIntent);
8686 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008687 // Release with a delay so the receiving client has an opportunity to put in its
8688 // own request.
8689 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008690 }
8691
Chalard Jean46bfbf02022-02-02 00:56:25 +09008692 // networkAgent is only allowed to be null if notificationType is
8693 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8694 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008695 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008696 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008697 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008698 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008699 // Default request has no msgr. Also prevents callbacks from being invoked for
8700 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8701 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8702 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008703 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008704 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008705 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008706 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008707 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008708 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008709 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008710 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8711 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008712 }
Roshan Pius951c0032020-12-22 15:10:42 -08008713 final boolean includeLocationSensitiveInfo =
8714 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008715 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008716 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008717 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008718 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008719 networkCapabilitiesRestrictedForCallerPermissions(
8720 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8721 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008722 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008723 nri.mCallingAttributionTag);
8724 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008725 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8726 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008727 // For this notification, arg1 contains the blocked status.
8728 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008729 break;
8730 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008731 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008732 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008733 break;
8734 }
8735 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008736 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008737 final NetworkCapabilities netCap =
8738 networkCapabilitiesRestrictedForCallerPermissions(
8739 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8740 putParcelable(
8741 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008742 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008743 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008744 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008745 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008746 break;
8747 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008748 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008749 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8750 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008751 break;
8752 }
junyulaif2c67e42018-08-07 19:50:45 +08008753 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008754 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008755 msg.arg1 = arg1;
8756 break;
8757 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008758 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008759 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008760 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008761 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008762 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008763 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008764 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008765 }
James Mattis45d81842021-01-10 14:24:24 -08008766 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008767 } catch (RemoteException e) {
8768 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008769 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008770 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008771 }
8772
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008773 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8774 bundle.putParcelable(t.getClass().getSimpleName(), t);
8775 }
8776
Chalard Jean0702f982021-09-16 21:50:07 +09008777 /**
8778 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8779 *
8780 * When a request should be assigned to a new network, it is normally lingered to give
8781 * time for apps to gracefully migrate their connections. When both networks are on the same
8782 * radio, but that radio can't do time-sharing efficiently, this may end up being
8783 * counter-productive because any traffic on the old network may drastically reduce the
8784 * performance of the new network.
8785 * The stack supports a configuration to let modem vendors state that their radio can't
8786 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8787 * from one cell network to another can't be done gracefully.
8788 *
8789 * @param oldNai the old network serving the request
8790 * @param newNai the new network serving the request
8791 * @return whether the switch can be graceful
8792 */
8793 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8794 @NonNull final NetworkAgentInfo newSatisfier) {
8795 if (mCellularRadioTimesharingCapable) return true;
8796 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8797 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8798 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8799 }
8800
Paul Jensenaf94b982014-09-30 15:37:41 -04008801 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008802 if (nai.numRequestNetworkRequests() != 0) {
8803 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8804 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008805 // Ignore listening and track default requests.
8806 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008807 loge("Dead network still had at least " + nr);
8808 break;
8809 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008810 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008811 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008812 }
8813
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008814 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8815 if (oldNetwork == null) {
8816 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8817 return;
8818 }
Chalard Jean49707572019-12-10 21:07:02 +09008819 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008820
8821 // If we get here it means that the last linger timeout for this network expired. So there
8822 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008823 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008824
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008825 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008826 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008827 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008828 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008829 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008830 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008831 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008832 }
8833
James Mattise3ef1912020-12-20 11:09:58 -08008834 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8835 boolean isDefaultChanged = false;
8836 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8837 final NetworkReassignment.RequestReassignment reassignment =
8838 changes.getReassignment(defaultRequestInfo);
8839 if (null == reassignment) {
8840 continue;
8841 }
8842 // reassignment only contains those instances where the satisfying network changed.
8843 isDefaultChanged = true;
8844 // Notify system services of the new default.
8845 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8846 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008847
James Mattise3ef1912020-12-20 11:09:58 -08008848 if (isDefaultChanged) {
8849 // Hold a wakelock for a short time to help apps in migrating to a new default.
8850 scheduleReleaseNetworkTransitionWakelock();
8851 }
8852 }
8853
8854 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8855 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8856 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8857 if (DBG) {
8858 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8859 }
Chalard Jean8e382112019-12-03 20:45:30 +09008860
James Mattisd31bdfa2020-12-23 16:37:26 -08008861 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8862 if (newDefaultNetwork != null) {
8863 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008864 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008865
James Mattisd31bdfa2020-12-23 16:37:26 -08008866 // Set an app level managed default and return since further processing only applies to the
8867 // default network.
8868 if (mDefaultRequest != nri) {
8869 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8870 return;
8871 }
8872
8873 makeDefaultNetwork(newDefaultNetwork);
8874
James Mattise3ef1912020-12-20 11:09:58 -08008875 if (oldDefaultNetwork != null) {
8876 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8877 }
8878 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008879 handleApplyDefaultProxy(null != newDefaultNetwork
8880 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8881 updateTcpBufferSizes(null != newDefaultNetwork
8882 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008883 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008884 }
8885
James Mattisd31bdfa2020-12-23 16:37:26 -08008886 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8887 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8888 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8889 try {
8890 if (VDBG) {
8891 log("Setting default network for " + nri
8892 + " using UIDs " + nri.getUids()
8893 + " with old network " + (oldDefaultNetwork != null
8894 ? oldDefaultNetwork.network().getNetId() : "null")
8895 + " and new network " + (newDefaultNetwork != null
8896 ? newDefaultNetwork.network().getNetId() : "null"));
8897 }
8898 if (nri.getUids().isEmpty()) {
8899 throw new IllegalStateException("makeDefaultForApps called without specifying"
8900 + " any applications to set as the default." + nri);
8901 }
8902 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008903 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008904 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008905 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008906 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008907 }
8908 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008909 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008910 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008911 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008912 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008913 }
8914 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008915 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008916 }
8917 }
8918
Junyu Lai35665cc2022-12-19 17:37:48 +08008919 /**
8920 * Collect restricted uid ranges for the given network and UserHandle, these uids
8921 * are not restricted for matched enterprise networks but being restricted for non-matched
8922 * enterprise networks and non-enterprise networks.
8923 */
8924 @NonNull
8925 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
8926 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
8927 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
8928 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
8929 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
8930
8931 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
8932 // The NC is built from a `ProfileNetworkPreference` which has only one
8933 // enterprise ID, so it's guaranteed to have exactly one.
8934 final int prefId = pref.capabilities.getEnterpriseIds()[0];
8935 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
8936 continue;
8937 }
8938 }
8939
8940 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
8941 pref.capabilities.getUidRanges())) {
8942 throw new IllegalArgumentException(
8943 "Overlapping uid range in preference: " + pref);
8944 }
8945 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
8946 }
8947 return restrictedUidRanges;
8948 }
8949
8950 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08008951 // Netd command is not implemented before U.
8952 if (!SdkLevel.isAtLeastU()) return;
8953
Junyu Lai35665cc2022-12-19 17:37:48 +08008954 ensureRunningOnConnectivityServiceThread();
8955 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
8956 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
8957 .getUserHandles(true /* excludeDying */);
8958 if (users.isEmpty()) {
8959 throw new IllegalStateException("No user is available");
8960 }
8961
8962 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8963 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
8964 for (final UserHandle user : users) {
8965 final ArraySet<UidRange> restrictedUidRanges =
8966 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
8967 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
8968 UidRange.createForUser(user), restrictedUidRanges));
8969 }
8970
8971 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
8972 configs.add(new NativeUidRangeConfig(
8973 nai.network.netId, rangesParcel, 0 /* subPriority */));
8974 }
8975
8976 // The netd API replaces the previous configs with the current configs.
8977 // Thus, for network disconnection or preference removal, no need to
8978 // unset previous config. Instead, collecting all currently needed
8979 // configs and issue to netd.
8980 try {
8981 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
8982 } catch (ServiceSpecificException e) {
8983 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08008984 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08008985 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08008986 // Netd died. This will cause a runtime restart anyway.
8987 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08008988 }
8989 }
8990
James Mattisd31bdfa2020-12-23 16:37:26 -08008991 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8992 try {
8993 if (null != newDefaultNetwork) {
8994 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8995 } else {
8996 mNetd.networkClearDefault();
8997 }
8998 } catch (RemoteException | ServiceSpecificException e) {
8999 loge("Exception setting default network :" + e);
9000 }
9001 }
9002
Chalard Jean05cbe972019-12-09 11:50:38 +09009003 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009004 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009005 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009006 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009007 processNewlySatisfiedListenRequests(nai);
9008 }
9009
9010 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009011 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9012 if (nri.isMultilayerRequest()) {
9013 continue;
9014 }
9015 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009016 if (!nr.isListen()) continue;
9017 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009018 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009019 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9020 }
9021 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009022 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009023
Chalard Jeancd397a22019-11-22 22:33:33 +09009024 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009025 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9026 if (nri.isMultilayerRequest()) {
9027 continue;
9028 }
9029 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009030 if (!nr.isListen()) continue;
9031 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9032 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009033 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009034 }
9035 }
9036 }
9037
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009038 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009039 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009040 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009041 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009042 @Nullable public final NetworkRequest mOldNetworkRequest;
9043 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009044 @Nullable public final NetworkAgentInfo mOldNetwork;
9045 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009046 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009047 @Nullable final NetworkRequest oldNetworkRequest,
9048 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009049 @Nullable final NetworkAgentInfo oldNetwork,
9050 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009051 mNetworkRequestInfo = networkRequestInfo;
9052 mOldNetworkRequest = oldNetworkRequest;
9053 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009054 mOldNetwork = oldNetwork;
9055 mNewNetwork = newNetwork;
9056 }
Chalard Jean49707572019-12-10 21:07:02 +09009057
9058 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009059 final NetworkRequest requestToShow = null != mNewNetworkRequest
9060 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9061 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009062 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9063 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009064 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009065 }
9066
Chalard Jean46a62372019-12-10 21:25:24 +09009067 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009068
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009069 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009070 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009071 }
9072
9073 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009074 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009075 // The code is never supposed to add two reassignments of the same request. Make
9076 // sure this stays true, but without imposing this expensive check on all
9077 // reassignments on all user devices.
9078 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009079 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009080 throw new IllegalStateException("Trying to reassign ["
9081 + reassignment + "] but already have ["
9082 + existing + "]");
9083 }
9084 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009085 }
Chalard Jean46a62372019-12-10 21:25:24 +09009086 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009087 }
9088
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009089 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009090 // the passed request.
9091 @Nullable
9092 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009093 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009094 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009095 }
9096 return null;
9097 }
Chalard Jean49707572019-12-10 21:07:02 +09009098
9099 public String toString() {
9100 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9101 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009102 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009103 for (final RequestReassignment rr : getRequestReassignments()) {
9104 sj.add(rr.toString());
9105 }
9106 return sj.toString();
9107 }
9108
9109 public String debugString() {
9110 final StringBuilder sb = new StringBuilder();
9111 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009112 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009113 for (final RequestReassignment rr : getRequestReassignments()) {
9114 sb.append("\n ").append(rr);
9115 }
9116 return sb.append("\n").toString();
9117 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009118 }
9119
Chalard Jean24344d72019-12-04 13:32:31 +09009120 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009121 @Nullable final NetworkRequest previousRequest,
9122 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009123 @Nullable final NetworkAgentInfo previousSatisfier,
9124 @Nullable final NetworkAgentInfo newSatisfier,
9125 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009126 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009127 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009128 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009129 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009130 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009131 }
James Mattisa076c532020-12-02 14:12:41 -08009132 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009133 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009134 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009135 // If this network switch can't be supported gracefully, the request is not
9136 // lingered. This allows letting go of the network sooner to reclaim some
9137 // performance on the new network, since the radio can't do both at the same
9138 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009139 //
9140 // Also don't linger the request if the old network has been destroyed.
9141 // A destroyed network does not provide actual network connectivity, so
9142 // lingering it is not useful. In particular this ensures that a destroyed
9143 // network is outscored by its replacement,
9144 // then it is torn down immediately instead of being lingered, and any apps that
9145 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009146 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9147 }
Chalard Jean24344d72019-12-04 13:32:31 +09009148 } else {
9149 if (VDBG || DDBG) log(" accepting network in place of null");
9150 }
junyulai0ac374f2020-12-14 18:41:52 +08009151
9152 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9153 // and immediately satisfies a request then remove the timer. This will happen for
9154 // all networks except in the case of an underlying network for a VCN.
9155 if (newSatisfier.isNascent()) {
9156 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009157 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009158 }
9159
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009160 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009161 newSatisfier.unlingerRequest(newRequest.requestId);
9162 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009163 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009164 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009165 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009166 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009167 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009168 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009169 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009170 }
James Mattisa076c532020-12-02 14:12:41 -08009171 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009172 }
James Mattisa076c532020-12-02 14:12:41 -08009173 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009174 }
9175
James Mattisa076c532020-12-02 14:12:41 -08009176 /**
9177 * This function is triggered when something can affect what network should satisfy what
9178 * request, and it computes the network reassignment from the passed collection of requests to
9179 * network match to the one that the system should now have. That data is encoded in an
9180 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9181 * satisfier.
9182 *
9183 * After the reassignment is computed, it is applied to the state objects.
9184 *
9185 * @param networkRequests the nri objects to evaluate for possible network reassignment
9186 * @return NetworkReassignment listing of proposed network assignment changes
9187 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009188 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009189 private NetworkReassignment computeNetworkReassignment(
9190 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009191 final NetworkReassignment changes = new NetworkReassignment();
9192
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009193 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009194 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009195 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009196 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009197 }
Chalard Jean857a1712019-12-10 21:08:07 +09009198
James Mattisa076c532020-12-02 14:12:41 -08009199 for (final NetworkRequestInfo nri : networkRequests) {
9200 // Non-multilayer listen requests can be ignored.
9201 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9202 continue;
9203 }
9204 NetworkAgentInfo bestNetwork = null;
9205 NetworkRequest bestRequest = null;
9206 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009207 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009208 // Stop evaluating as the highest possible priority request is satisfied.
9209 if (null != bestNetwork) {
9210 bestRequest = req;
9211 break;
9212 }
9213 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009214 if (null == bestNetwork && isDefaultBlocked(nri)) {
9215 // Remove default networking if disallowed for managed default requests.
9216 bestNetwork = mNoServiceNetwork;
9217 }
9218 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009219 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009220 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009221 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009222 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009223 }
9224 return changes;
9225 }
9226
James Mattisa076c532020-12-02 14:12:41 -08009227 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9228 return new HashSet<>(mNetworkRequests.values());
9229 }
9230
Paul Jensenc88b39b2015-06-16 14:27:36 -04009231 /**
James Mattisa076c532020-12-02 14:12:41 -08009232 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009233 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009234 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009235 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009236 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9237 }
9238
9239 /**
9240 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9241 * being disconnected.
9242 */
9243 private void rematchNetworksAndRequests(
9244 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9245 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009246 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009247 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009248 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009249 final long computed = SystemClock.elapsedRealtime();
9250 applyNetworkReassignment(changes, start);
9251 final long applied = SystemClock.elapsedRealtime();
9252 issueNetworkNeeds();
9253 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009254 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009255 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9256 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009257 log(changes.debugString());
9258 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009259 // Shorter form, only one line of log
9260 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9261 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009262 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009263 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009264
Chalard Jeand7f762d2019-12-10 19:01:29 +09009265 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009266 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009267 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009268
9269 // Since most of the time there are only 0 or 1 background networks, it would probably
9270 // be more efficient to just use an ArrayList here. TODO : measure performance
9271 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9272 for (final NetworkAgentInfo nai : nais) {
9273 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9274 }
9275
Chalard Jeand7f762d2019-12-10 19:01:29 +09009276 // First, update the lists of satisfied requests in the network agents. This is necessary
9277 // because some code later depends on this state to be correct, most prominently computing
9278 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009279 for (final NetworkReassignment.RequestReassignment event :
9280 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009281 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9282 event.mOldNetworkRequest, event.mNewNetworkRequest,
9283 event.mOldNetwork, event.mNewNetwork,
9284 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009285 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009286
James Mattise3ef1912020-12-20 11:09:58 -08009287 // Process default network changes if applicable.
9288 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009289
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009290 // Notify requested networks are available after the default net is switched, but
9291 // before LegacyTypeTracker sends legacy broadcasts
9292 for (final NetworkReassignment.RequestReassignment event :
9293 changes.getRequestReassignments()) {
9294 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009295 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009296 } else {
James Mattisa076c532020-12-02 14:12:41 -08009297 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009298 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009299 }
9300 }
9301
junyulai0ac374f2020-12-14 18:41:52 +08009302 // Update the inactivity state before processing listen callbacks, because the background
9303 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009304 // just yet though, because they have to be sent after the listens are processed to keep
9305 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009306 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009307 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009308 // Rematching may have altered the inactivity state of some networks, so update all
9309 // inactivity timers. updateInactivityState reads the state from the network agent
9310 // and does nothing if the state has not changed : the source of truth is controlled
9311 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9312 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009313 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009314 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009315 }
9316 }
9317
Chalard Jeanb10ab412019-12-11 14:12:30 +09009318 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009319 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009320 // Process listen requests and update capabilities if the background state has
9321 // changed for this network. For consistency with previous behavior, send onLost
9322 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009323 processNewlyLostListenRequests(nai);
9324 if (oldBackground != nai.isBackgroundNetwork()) {
9325 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009326 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009327 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009328 }
9329
junyulai0ac374f2020-12-14 18:41:52 +08009330 for (final NetworkAgentInfo nai : inactiveNetworks) {
9331 // For nascent networks, if connecting with no foreground request, skip broadcasting
9332 // LOSING for backward compatibility. This is typical when mobile data connected while
9333 // wifi connected with mobile data always-on enabled.
9334 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009335 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009336 }
9337
James Mattise3ef1912020-12-20 11:09:58 -08009338 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009339
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009340 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009341 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009342 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009343 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009344 // This network has active linger timers and no requests, but is not
9345 // lingering. Linger it.
9346 //
9347 // One way (the only way?) this can happen if this network is unvalidated
9348 // and became unneeded due to another network improving its score to the
9349 // point where this network will no longer be able to satisfy any requests
9350 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009351 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009352 notifyNetworkLosing(nai, now);
9353 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009354 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009355 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009356 teardownUnneededNetwork(nai);
9357 }
9358 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009359 }
9360 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009361
Chalard Jean62edfd82019-12-02 18:39:29 +09009362 /**
9363 * Apply a change in background state resulting from rematching networks with requests.
9364 *
9365 * During rematch, a network may change background states by starting to satisfy or stopping
9366 * to satisfy a foreground request. Listens don't count for this. When a network changes
9367 * background states, its capabilities need to be updated and callbacks fired for the
9368 * capability change.
9369 *
9370 * @param nai The network that changed background states
9371 */
9372 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9373 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9374 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9375 updateNetworkPermissions(nai, newNc);
9376 nai.getAndSetNetworkCapabilities(newNc);
9377 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9378 }
9379
Chalard Jeanf0344532019-11-19 19:23:38 +09009380 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009381 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009382 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009383 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9384 changes.getReassignment(mDefaultRequest);
9385 final NetworkAgentInfo oldDefaultNetwork =
9386 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9387 final NetworkAgentInfo newDefaultNetwork =
9388 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009389
Chalard Jean5b409c72021-02-04 13:12:59 +09009390 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009391 // Maintain the illusion : since the legacy API only understands one network at a time,
9392 // if the default network changed, apps should see a disconnected broadcast for the
9393 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009394 if (oldDefaultNetwork != null) {
9395 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9396 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009397 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009398 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009399 // The new default network can be newly null if and only if the old default
9400 // network doesn't satisfy the default request any more because it lost a
9401 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009402 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009403 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009404 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009405 }
9406 }
9407
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009408 // Now that all the callbacks have been sent, send the legacy network broadcasts
9409 // as needed. This is necessary so that legacy requests correctly bind dns
9410 // requests to this network. The legacy users are listening for this broadcast
9411 // and will generally do a dns request so they can ensureRouteToHost and if
9412 // they do that before the callbacks happen they'll use the default network.
9413 //
9414 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9415 // callbacks, but if apps can receive the broadcast before the callback, they still might
9416 // have an inconsistent view of networking.
9417 //
9418 // This *does* introduce a race where if the user uses the new api
9419 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9420 // they may get old info. Reverse this after the old startUsing api is removed.
9421 // This is on top of the multiple intent sequencing referenced in the todo above.
9422 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009423 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009424 addNetworkToLegacyTypeTracker(nai);
9425 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009426 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009427 }
9428
Chalard Jean0354d8c2021-01-12 10:58:56 +09009429 private void issueNetworkNeeds() {
9430 ensureRunningOnConnectivityServiceThread();
9431 for (final NetworkOfferInfo noi : mNetworkOffers) {
9432 issueNetworkNeeds(noi);
9433 }
9434 }
9435
9436 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9437 ensureRunningOnConnectivityServiceThread();
9438 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9439 informOffer(nri, noi.offer, mNetworkRanker);
9440 }
9441 }
9442
9443 /**
9444 * Inform a NetworkOffer about any new situation of a request.
9445 *
9446 * This function handles updates to offers. A number of events may happen that require
9447 * updating the registrant for this offer about the situation :
9448 * • The offer itself was updated. This may lead the offer to no longer being able
9449 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9450 * or conversely being strengthened enough to beat the satisfier (and therefore
9451 * start being needed)
9452 * • The network satisfying a request changed (including cases where the request
9453 * starts or stops being satisfied). The new network may be a stronger or weaker
9454 * match than the old one, possibly affecting whether the offer is needed.
9455 * • The network satisfying a request updated their score. This may lead the offer
9456 * to no longer be able to beat it if the current satisfier got better, or
9457 * conversely start being a good choice if the current satisfier got weaker.
9458 *
9459 * @param nri The request
9460 * @param offer The offer. This may be an updated offer.
9461 */
9462 private static void informOffer(@NonNull NetworkRequestInfo nri,
9463 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9464 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9465 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009466
9467 // Multi-layer requests have a currently active request, the one being satisfied.
9468 // Since the system will try to bring up a better network than is currently satisfying
9469 // the request, NetworkProviders need to be told the offers matching the requests *above*
9470 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9471 // not needed, and the offer is needed for the active request iff the offer can beat
9472 // the satisfier.
9473 // For non-multilayer requests, the logic above gracefully degenerates to only the
9474 // last case.
9475 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9476 // providers that the offer is needed for this request, until the active request is found.
9477 // In a second phase, deal with the currently active request. In a third phase, inform
9478 // the providers that offer is unneeded for the remaining requests.
9479
9480 // First phase : inform providers of all requests above the active request.
9481 int i;
9482 for (i = 0; nri.mRequests.size() > i; ++i) {
9483 final NetworkRequest request = nri.mRequests.get(i);
9484 if (activeRequest == request) break; // Found the active request : go to phase 2
9485 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9486 // Since this request is higher-priority than the one currently satisfied, if the
9487 // offer can satisfy it, the provider should try and bring up the network for sure ;
9488 // no need to even ask the ranker – an offer that can satisfy is always better than
9489 // no network. Hence tell the provider so unless it already knew.
9490 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9491 offer.onNetworkNeeded(request);
9492 }
9493 }
9494
9495 // Second phase : deal with the active request (if any)
9496 if (null != activeRequest && activeRequest.isRequest()) {
9497 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009498 // If an offer can satisfy the request, it is considered needed if it is currently
9499 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009500 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009501 && satisfier.factorySerialNumber == offer.providerId
9502 && activeRequest.canBeSatisfiedBy(offer.caps);
9503 final boolean newNeeded = currentlyServing
9504 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009505 if (newNeeded != oldNeeded) {
9506 if (newNeeded) {
9507 offer.onNetworkNeeded(activeRequest);
9508 } else {
9509 // The offer used to be able to beat the satisfier. Now it can't.
9510 offer.onNetworkUnneeded(activeRequest);
9511 }
9512 }
9513 }
9514
9515 // Third phase : inform the providers that the offer isn't needed for any request
9516 // below the active one.
9517 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9518 final NetworkRequest request = nri.mRequests.get(i);
9519 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9520 // Since this request is lower-priority than the one currently satisfied, if the
9521 // offer can satisfy it, the provider should not try and bring up the network.
9522 // Hence tell the provider so unless it already knew.
9523 if (offer.neededFor(request)) {
9524 offer.onNetworkUnneeded(request);
9525 }
9526 }
9527 }
9528
Chalard Jean61c79252019-11-07 23:07:32 +09009529 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9530 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9531 NetworkRequest nr = nai.requestAt(i);
9532 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9533 // legacy type tracker filters out repeat adds
9534 mLegacyTypeTracker.add(nr.legacyType, nai);
9535 }
9536 }
9537
9538 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009539 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009540 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9541 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9542 if (nai.isVPN()) {
9543 mLegacyTypeTracker.add(TYPE_VPN, nai);
9544 }
9545 }
9546
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009547 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009548 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009549 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009550 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009551 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009552 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009553
Chalard Jean254bd162022-08-25 13:04:51 +09009554 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009555 // Don't repeat publish.
9556 if (newInetCondition == mDefaultInetConditionPublished) return;
9557
9558 mDefaultInetConditionPublished = newInetCondition;
9559 sendInetConditionBroadcast(nai.networkInfo);
9560 }
9561
Chalard Jeand61375d2020-01-14 22:46:36 +09009562 @NonNull
9563 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9564 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009565 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009566 final boolean suspended =
9567 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9568 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9569 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9570 // state. This is because the network could have been suspended before connecting,
9571 // or it could be disconnecting while being suspended, and in both these cases
9572 // the state should not be overridden. Note that the only detailed state that
9573 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9574 // worry about multiple different substates of CONNECTED.
9575 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9576 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009577 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9578 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9579 // network agent is created, then goes to suspended, then goes out of suspended without
9580 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009581 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009582 ? NetworkInfo.DetailedState.CONNECTED
9583 : NetworkInfo.DetailedState.CONNECTING,
9584 info.getReason(),
9585 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009586 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009587 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009588 return newInfo;
9589 }
9590
9591 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9592 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9593
Erik Kline99f301b2017-02-15 19:59:17 +09009594 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009595 NetworkInfo oldInfo = null;
9596 synchronized (networkAgent) {
9597 oldInfo = networkAgent.networkInfo;
9598 networkAgent.networkInfo = newInfo;
9599 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009600
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009601 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009602 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9603 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009604 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009605
Chalard Jean254bd162022-08-25 13:04:51 +09009606 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009607 && (state == NetworkInfo.State.CONNECTED
9608 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009609
9610 // A network that has just connected has zero requests and is thus a foreground network.
9611 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9612
Luke Huangfdd11f82019-04-09 18:41:49 +08009613 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009614 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009615 // Initialize the network's capabilities to their starting values according to the
9616 // underlying networks. This ensures that the capabilities are correct before
9617 // anything happens to the network.
9618 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009619 }
Chalard Jean254bd162022-08-25 13:04:51 +09009620 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009621 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009622 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009623 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009624 }
9625
Chalard Jean254bd162022-08-25 13:04:51 +09009626 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9627 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009628
lucaslin45e639b2019-04-03 17:09:28 +08009629 // NetworkCapabilities need to be set before sending the private DNS config to
9630 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009631 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9632
Erik Kline9a62f012018-03-21 07:18:33 -07009633 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009634 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9635 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009636
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009637 // If a rate limit has been configured and is applicable to this network (network
9638 // provides internet connectivity), apply it. The tc police filter cannot be attached
9639 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9640 // updateInterfaces -> INetd#networkAddInterface.
9641 // Note: in case of a system server crash, the NetworkController constructor in netd
9642 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9643 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9644 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9645 mIngressRateLimit);
9646 }
9647
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009648 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9649 // command must be sent after updating LinkProperties to maximize chances of
9650 // NetworkMonitor seeing the correct LinkProperties when starting.
9651 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009652 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009653 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009654 }
Chalard Jeand4900722022-02-06 12:25:38 +09009655 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9656 params.networkAgentConfig = networkAgent.networkAgentConfig;
9657 params.networkCapabilities = networkAgent.networkCapabilities;
9658 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9659 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009660 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9661 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9662 // call that would cause a Log.wtf to be emitted from the system_server process, and
9663 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9664 // process to check the interface version, just use an SDK check. NetworkStack will
9665 // always be new enough when running on T+.
9666 if (SdkLevel.isAtLeastT()) {
9667 networkAgent.networkMonitor().notifyNetworkConnected(params);
9668 } else {
9669 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9670 params.networkCapabilities);
9671 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009672 final long delay = activelyPreferBadWifi()
9673 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9674 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9675 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009676
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009677 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9678 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9679 // capabilities, so it only needs to be done once on initial connect, not every time the
9680 // network's capabilities change. Note that we do this before rematching the network,
9681 // so we could decide to tear it down immediately afterwards. That's fine though - on
9682 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9683 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009684 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009685
junyulai0ac374f2020-12-14 18:41:52 +08009686 // Before first rematching networks, put an inactivity timer without any request, this
9687 // allows {@code updateInactivityState} to update the state accordingly and prevent
9688 // tearing down for any {@code unneeded} evaluation in this period.
9689 // Note that the timer will not be rescheduled since the expiry time is
9690 // fixed after connection regardless of the network satisfying other requests or not.
9691 // But it will be removed as soon as the network satisfies a request for the first time.
9692 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9693 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009694 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009695
Paul Jensen05e85ee2014-09-11 11:00:39 -04009696 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009697 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009698
9699 // This has to happen after matching the requests, because callbacks are just requests.
9700 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009701 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009702 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009703 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009704 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009705 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009706 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009707 if (networkAgent.isVPN()) {
9708 // As the active or bound network changes for apps, broadcast the default proxy, as
9709 // apps may need to update their proxy data. This is called after disconnecting from
9710 // VPN to make sure we do not broadcast the old proxy data.
9711 // TODO(b/122649188): send the broadcast only to VPN users.
9712 mProxyTracker.sendProxyBroadcast();
9713 }
Chalard Jean254bd162022-08-25 13:04:51 +09009714 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9715 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009716 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009717 }
9718 }
9719
Chalard Jean28018572020-12-21 18:36:52 +09009720 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009721 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9722 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009723 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009724 }
9725
Erik Kline99f301b2017-02-15 19:59:17 +09009726 // Notify only this one new request of the current state. Transfer all the
9727 // current state by calling NetworkCapabilities and LinkProperties callbacks
9728 // so that callers can be guaranteed to have as close to atomicity in state
9729 // transfer as can be supported by this current API.
9730 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009731 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009732 if (nri.mPendingIntent != null) {
9733 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9734 // Attempt no subsequent state pushes where intents are involved.
9735 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009736 }
Erik Kline99f301b2017-02-15 19:59:17 +09009737
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009738 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009739 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009740 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9741 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9742 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009743 }
9744
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009745 // Notify the requests on this NAI that the network is now lingered.
9746 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009747 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009748 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9749 }
9750
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009751 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9752 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9753 return vpnBlocked
9754 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9755 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9756 }
9757
9758 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9759 if (blockedReasons == BLOCKED_REASON_NONE) {
9760 mUidBlockedReasons.delete(uid);
9761 } else {
9762 mUidBlockedReasons.put(uid, blockedReasons);
9763 }
9764 }
9765
junyulaif2c67e42018-08-07 19:50:45 +08009766 /**
9767 * Notify of the blocked state apps with a registered callback matching a given NAI.
9768 *
9769 * Unlike other callbacks, blocked status is different between each individual uid. So for
9770 * any given nai, all requests need to be considered according to the uid who filed it.
9771 *
9772 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009773 * @param oldMetered True if the previous network capabilities were metered.
9774 * @param newMetered True if the current network capabilities are metered.
9775 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9776 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009777 */
9778 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009779 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9780 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009781
9782 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9783 NetworkRequest nr = nai.requestAt(i);
9784 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009785
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009786 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9787 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9788 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009789 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009790 : oldVpnBlocked;
9791
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009792 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9793 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9794 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009795 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009796 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009797 }
9798 }
9799 }
9800
9801 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009802 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009803 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009804 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009805 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009806 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009807 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009808 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009809 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009810
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009811 final int oldBlockedState = getBlockedState(
9812 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9813 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9814 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009815 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009816 }
junyulaif2c67e42018-08-07 19:50:45 +08009817 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9818 NetworkRequest nr = nai.requestAt(i);
9819 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009820 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009821 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9822 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009823 }
9824 }
9825 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009826 }
9827
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009828 @VisibleForTesting
9829 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009830 // The NetworkInfo we actually send out has no bearing on the real
9831 // state of affairs. For example, if the default connection is mobile,
9832 // and a request for HIPRI has just gone away, we need to pretend that
9833 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9834 // the state to DISCONNECTED, even though the network is of type MOBILE
9835 // and is still connected.
9836 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9837 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009838 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009839 if (state != DetailedState.DISCONNECTED) {
9840 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009841 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009842 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009843 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009844 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9845 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9846 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9847 if (info.isFailover()) {
9848 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9849 nai.networkInfo.setFailover(false);
9850 }
9851 if (info.getReason() != null) {
9852 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9853 }
9854 if (info.getExtraInfo() != null) {
9855 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9856 }
9857 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009858 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009859 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009860 if (newDefaultAgent != null) {
9861 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9862 newDefaultAgent.networkInfo);
9863 } else {
9864 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9865 }
9866 }
9867 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9868 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009869 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009870 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009871 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009872 }
9873 }
9874 }
9875
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009876 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009877 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009878 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009879 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009880 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009881 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9882 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009883 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9884 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009885 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009886 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009887 } else {
9888 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9889 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009890 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009891 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009892
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009893 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9894 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9895 }
9896
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009897 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009898 * Returns the list of all interfaces that could be used by network traffic that does not
9899 * explicitly specify a network. This includes the default network, but also all VPNs that are
9900 * currently connected.
9901 *
9902 * Must be called on the handler thread.
9903 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009904 @NonNull
9905 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009906 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009907 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009908 final Set<Integer> activeNetIds = new ArraySet<>();
9909 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9910 if (nri.isBeingSatisfied()) {
9911 activeNetIds.add(nri.getSatisfier().network().netId);
9912 }
9913 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009914 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009915 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009916 defaultNetworks.add(nai.network);
9917 }
9918 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009919 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009920 }
9921
9922 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009923 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9924 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009925 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009926 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009927 ensureRunningOnConnectivityServiceThread();
9928 String activeIface = null;
9929 LinkProperties activeLinkProperties = getActiveLinkProperties();
9930 if (activeLinkProperties != null) {
9931 activeIface = activeLinkProperties.getInterfaceName();
9932 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009933
junyulai2050bed2021-01-23 09:46:34 +08009934 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009935 try {
junyulaide41fc22021-01-22 22:46:01 +08009936 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009937 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009938 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9939 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009940 } catch (Exception ignored) {
9941 }
9942 }
9943
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009944 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009945 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009946 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009947 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009948 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009949
9950 if (!TextUtils.isEmpty(settingUrl)) {
9951 return settingUrl;
9952 }
9953
9954 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009955 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009956 if (!TextUtils.isEmpty(settingUrl)) {
9957 return settingUrl;
9958 }
9959
9960 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009961 }
9962
9963 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009964 public void startNattKeepalive(Network network, int intervalSeconds,
9965 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009966 enforceKeepalivePermission();
9967 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009968 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00009969 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
9970 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +00009971 // false and set the underpinned network to null because there is no way and no
9972 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
9973 // deprecated method.
9974 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009975 }
9976
9977 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009978 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009979 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +00009980 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -07009981 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009982 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009983 mKeepaliveTracker.startNattKeepalive(
9984 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +00009985 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
9986 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -07009987 } finally {
9988 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9989 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009990 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9991 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009992 }
9993 }
junyulaid05a1922019-01-15 11:32:44 +08009994 }
9995
9996 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009997 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009998 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009999 try {
10000 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010001 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010002 mKeepaliveTracker.startTcpKeepalive(
10003 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10004 } finally {
10005 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10006 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010007 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10008 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010009 }
10010 }
junyulai0835a1e2019-01-08 20:04:33 +080010011 }
10012
10013 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010014 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010015 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010016 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10017 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010018 }
10019
10020 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010021 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010022 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010023
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010024 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010025 final long token = Binder.clearCallingIdentity();
10026 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010027 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10028 UserHandle.getUserHandleForUid(uid))) {
10029 return;
10030 }
10031
Heemin Seogdb8489d2019-06-12 09:21:44 -070010032 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10033 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010034
10035 // Turn airplane mode off
10036 setAirplaneMode(false);
10037
10038 // restore private DNS settings to default mode (opportunistic)
10039 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10040 UserHandle.getUserHandleForUid(uid))) {
10041 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10042 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10043 }
10044
10045 Settings.Global.putString(mContext.getContentResolver(),
10046 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010047 } finally {
10048 Binder.restoreCallingIdentity(token);
10049 }
Stuart Scottd5463642015-04-02 18:00:02 -070010050 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010051
Ricky Wai7097cc92018-01-23 04:09:45 +000010052 @Override
10053 public byte[] getNetworkWatchlistConfigHash() {
10054 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10055 if (nwm == null) {
10056 loge("Unable to get NetworkWatchlistManager");
10057 return null;
10058 }
10059 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10060 return nwm.getWatchlistConfigHash();
10061 }
10062
Hugo Benichibe0c7652016-05-31 16:28:06 +090010063 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010064 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010065 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010066 }
Hugo Benichif4210292017-04-21 15:07:12 +090010067
10068 private static boolean toBool(int encodedBoolean) {
10069 return encodedBoolean != 0; // Only 0 means false.
10070 }
10071
10072 private static int encodeBool(boolean b) {
10073 return b ? 1 : 0;
10074 }
mswest4632928412018-03-12 10:34:34 -070010075
10076 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010077 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10078 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10079 @NonNull String[] args) {
10080 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10081 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010082 }
10083
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010084 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010085 @Override
10086 public int onCommand(String cmd) {
10087 if (cmd == null) {
10088 return handleDefaultCommands(cmd);
10089 }
10090 final PrintWriter pw = getOutPrintWriter();
10091 try {
10092 switch (cmd) {
10093 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010094 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10095 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010096 final String action = getNextArg();
10097 if ("enable".equals(action)) {
10098 setAirplaneMode(true);
10099 return 0;
10100 } else if ("disable".equals(action)) {
10101 setAirplaneMode(false);
10102 return 0;
10103 } else if (action == null) {
10104 final ContentResolver cr = mContext.getContentResolver();
10105 final int enabled = Settings.Global.getInt(cr,
10106 Settings.Global.AIRPLANE_MODE_ON);
10107 pw.println(enabled == 0 ? "disabled" : "enabled");
10108 return 0;
10109 } else {
10110 onHelp();
10111 return -1;
10112 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010113 case "reevaluate":
10114 // Usage : adb shell cmd connectivity reevaluate <netId>
10115 // If netId is omitted, then reevaluate the default network
10116 final String netId = getNextArg();
10117 final NetworkAgentInfo nai;
10118 if (null == netId) {
10119 // Note that the command is running on the wrong thread to call this,
10120 // so this could in principle return stale data. But it can't crash.
10121 nai = getDefaultNetwork();
10122 } else {
10123 // If netId can't be parsed, this throws NumberFormatException, which
10124 // is passed back to adb who prints it.
10125 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10126 }
10127 if (null == nai) {
10128 pw.println("Unknown network (net ID not found or no default network)");
10129 return 0;
10130 }
10131 Log.d(TAG, "Reevaluating network " + nai.network);
10132 reportNetworkConnectivity(nai.network, !nai.isValidated());
10133 return 0;
mswest4632928412018-03-12 10:34:34 -070010134 default:
10135 return handleDefaultCommands(cmd);
10136 }
10137 } catch (Exception e) {
10138 pw.println(e);
10139 }
10140 return -1;
10141 }
10142
10143 @Override
10144 public void onHelp() {
10145 PrintWriter pw = getOutPrintWriter();
10146 pw.println("Connectivity service commands:");
10147 pw.println(" help");
10148 pw.println(" Print this help text.");
10149 pw.println(" airplane-mode [enable|disable]");
10150 pw.println(" Turn airplane mode on or off.");
10151 pw.println(" airplane-mode");
10152 pw.println(" Get airplane mode.");
10153 }
10154 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010155
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010156 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010157 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10158 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10159 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010160 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010161 }
10162
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010163 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10164 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010165 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10166 final TransportInfo newInfo = nc.getTransportInfo();
10167 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10168 return;
10169 }
10170 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010171 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010172 }
10173 }
10174
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010175 /**
10176 * @param connectionInfo the connection to resolve.
10177 * @return {@code uid} if the connection is found and the app has permission to observe it
10178 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10179 * connection is not found.
10180 */
10181 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010182 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10183 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10184 }
10185
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010186 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010187 connectionInfo.local, connectionInfo.remote);
10188
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010189 if (uid == INVALID_UID) return uid; // Not found.
10190
10191 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10192 // VPN, if any, that applies to the UID that owns the connection.
10193 if (checkNetworkStackPermission()) return uid;
10194
10195 final NetworkAgentInfo vpn = getVpnForUid(uid);
10196 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010197 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010198 return INVALID_UID;
10199 }
10200
10201 return uid;
10202 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010203
Benedict Wong493e04b2018-11-09 14:45:34 -080010204 /**
10205 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10206 *
10207 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10208 */
10209 @Override
10210 public IBinder startOrGetTestNetworkService() {
10211 synchronized (mTNSLock) {
10212 TestNetworkService.enforceTestNetworkPermissions(mContext);
10213
10214 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010215 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010216 }
10217
10218 return mTNS;
10219 }
10220 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010221
Cody Kesting73708bf2019-12-18 10:57:50 -080010222 /**
10223 * Handler used for managing all Connectivity Diagnostics related functions.
10224 *
10225 * @see android.net.ConnectivityDiagnosticsManager
10226 *
10227 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10228 */
10229 @VisibleForTesting
10230 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010231 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10232
Cody Kesting73708bf2019-12-18 10:57:50 -080010233 /**
10234 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10235 * android.net.ConnectivityDiagnosticsManager}.
10236 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10237 * NetworkRequestInfo to be registered
10238 */
10239 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10240
10241 /**
10242 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10243 * android.net.ConnectivityDiagnosticsManager}.
10244 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10245 * arg1 = the uid of the caller
10246 */
10247 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10248
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010249 /**
10250 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010251 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010252 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10253 * NetworkMonitor.
10254 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010255 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010256 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010257
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010258 /**
10259 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10260 * been detected on the network.
10261 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10262 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10263 * arg2 = NetID.
10264 * data = PersistableBundle of extras passed from NetworkMonitor.
10265 */
10266 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10267
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010268 /**
10269 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10270 * the platform. This event will invoke {@link
10271 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10272 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010273 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010274 */
10275 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10276
Cody Kesting73708bf2019-12-18 10:57:50 -080010277 private ConnectivityDiagnosticsHandler(Looper looper) {
10278 super(looper);
10279 }
10280
10281 @Override
10282 public void handleMessage(Message msg) {
10283 switch (msg.what) {
10284 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10285 handleRegisterConnectivityDiagnosticsCallback(
10286 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10287 break;
10288 }
10289 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10290 handleUnregisterConnectivityDiagnosticsCallback(
10291 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10292 break;
10293 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010294 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010295 final ConnectivityReportEvent reportEvent =
10296 (ConnectivityReportEvent) msg.obj;
10297
Aaron Huang959d3642021-01-21 15:47:41 +080010298 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010299 break;
10300 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010301 case EVENT_DATA_STALL_SUSPECTED: {
10302 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010303 final Pair<Long, PersistableBundle> arg =
10304 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010305 if (nai == null) break;
10306
Aaron Huang959d3642021-01-21 15:47:41 +080010307 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010308 break;
10309 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010310 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010311 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010312 break;
10313 }
10314 default: {
10315 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10316 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010317 }
10318 }
10319 }
10320
10321 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10322 @VisibleForTesting
10323 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10324 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10325 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010326 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010327
10328 @VisibleForTesting
10329 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010330 @NonNull IConnectivityDiagnosticsCallback cb,
10331 @NonNull NetworkRequestInfo nri,
10332 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010333 mCb = cb;
10334 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010335 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010336 }
10337
10338 @Override
10339 public void binderDied() {
10340 log("ConnectivityDiagnosticsCallback IBinder died.");
10341 unregisterConnectivityDiagnosticsCallback(mCb);
10342 }
10343 }
10344
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010345 /**
10346 * Class used for sending information from {@link
10347 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10348 */
10349 private static class NetworkTestedResults {
10350 private final int mNetId;
10351 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010352 @Nullable private final String mRedirectUrl;
10353
10354 private NetworkTestedResults(
10355 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10356 mNetId = netId;
10357 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010358 mRedirectUrl = redirectUrl;
10359 }
10360 }
10361
10362 /**
10363 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10364 * ConnectivityDiagnosticsHandler}.
10365 */
10366 private static class ConnectivityReportEvent {
10367 private final long mTimestampMillis;
10368 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010369 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010370
Aaron Huang959d3642021-01-21 15:47:41 +080010371 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10372 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010373 mTimestampMillis = timestampMillis;
10374 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010375 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010376 }
10377 }
10378
Cody Kestingf1120be2020-08-03 18:01:40 -070010379 /**
10380 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10381 * ConnectivityDiagnosticsHandler}.
10382 */
10383 private static class ReportedNetworkConnectivityInfo {
10384 public final boolean hasConnectivity;
10385 public final boolean isNetworkRevalidating;
10386 public final int reporterUid;
10387 @NonNull public final NetworkAgentInfo nai;
10388
10389 private ReportedNetworkConnectivityInfo(
10390 boolean hasConnectivity,
10391 boolean isNetworkRevalidating,
10392 int reporterUid,
10393 @NonNull NetworkAgentInfo nai) {
10394 this.hasConnectivity = hasConnectivity;
10395 this.isNetworkRevalidating = isNetworkRevalidating;
10396 this.reporterUid = reporterUid;
10397 this.nai = nai;
10398 }
10399 }
10400
Cody Kesting73708bf2019-12-18 10:57:50 -080010401 private void handleRegisterConnectivityDiagnosticsCallback(
10402 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10403 ensureRunningOnConnectivityServiceThread();
10404
10405 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010406 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010407 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10408
James Mattis64b8b0f2020-11-24 17:40:49 -080010409 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10410 // confusing for these networks to change when an NRI is satisfied in another layer.
10411 if (nri.isMultilayerRequest()) {
10412 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10413 + "network requests.");
10414 }
10415
Cody Kesting73708bf2019-12-18 10:57:50 -080010416 // This means that the client registered the same callback multiple times. Do
10417 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010418 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010419 if (VDBG) log("Diagnostics callback is already registered");
10420
10421 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10422 // incremented when the NetworkRequestInfo is created as part of
10423 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010424 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010425 return;
10426 }
10427
Cody Kesting31f1ff62020-03-05 10:46:02 -080010428 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010429
10430 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010431 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010432 } catch (RemoteException e) {
10433 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010434 return;
10435 }
10436
10437 // Once registered, provide ConnectivityReports for matching Networks
10438 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10439 synchronized (mNetworkForNetId) {
10440 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10441 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010442 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10443 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010444 matchingNetworks.add(nai);
10445 }
10446 }
10447 }
10448 for (final NetworkAgentInfo nai : matchingNetworks) {
10449 final ConnectivityReport report = nai.getConnectivityReport();
10450 if (report == null) {
10451 continue;
10452 }
10453 if (!checkConnectivityDiagnosticsPermissions(
10454 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10455 continue;
10456 }
10457
10458 try {
10459 cb.onConnectivityReportAvailable(report);
10460 } catch (RemoteException e) {
10461 // Exception while sending the ConnectivityReport. Move on to the next network.
10462 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010463 }
10464 }
10465
10466 private void handleUnregisterConnectivityDiagnosticsCallback(
10467 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10468 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010469 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010470
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010471 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10472 mConnectivityDiagnosticsCallbacks.remove(iCb);
10473 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010474 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10475 return;
10476 }
10477
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010478 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010479
Cody Kesting70fa2b22020-12-02 12:16:56 -080010480 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10481 // (if the Binder died)
10482 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10483 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010484 return;
10485 }
10486
Cody Kesting46cb1672020-03-04 13:35:20 -080010487 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10488 // incremented when the NetworkRequestInfo is created as part of
10489 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010490 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010491
Cody Kesting31f1ff62020-03-05 10:46:02 -080010492 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010493 }
10494
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010495 private void handleNetworkTestedWithExtras(
10496 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10497 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010498 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010499 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010500 final ConnectivityReport report =
10501 new ConnectivityReport(
10502 reportEvent.mNai.network,
10503 reportEvent.mTimestampMillis,
10504 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010505 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010506 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010507 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010508
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010509 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010510 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010511 for (final IConnectivityDiagnosticsCallback cb : results) {
10512 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010513 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010514 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010515 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010516 }
10517 }
10518 }
10519
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010520 private void handleDataStallSuspected(
10521 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10522 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010523 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010524 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010525 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010526 new DataStallReport(
10527 nai.network,
10528 timestampMillis,
10529 detectionMethod,
10530 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010531 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010532 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010533 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010534 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010535 for (final IConnectivityDiagnosticsCallback cb : results) {
10536 try {
10537 cb.onDataStallSuspected(report);
10538 } catch (RemoteException ex) {
10539 loge("Error invoking onDataStallSuspected", ex);
10540 }
10541 }
10542 }
10543
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010544 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010545 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10546 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10547 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10548
10549 // If the Network is being re-validated as a result of this call to
10550 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10551 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010552 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010553 getMatchingPermissionedCallbacks(
10554 nai,
10555 reportedNetworkConnectivityInfo.isNetworkRevalidating
10556 ? Process.INVALID_UID
10557 : reportedNetworkConnectivityInfo.reporterUid);
10558
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010559 for (final IConnectivityDiagnosticsCallback cb : results) {
10560 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010561 cb.onNetworkConnectivityReported(
10562 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010563 } catch (RemoteException ex) {
10564 loge("Error invoking onNetworkConnectivityReported", ex);
10565 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010566
10567 // If the Network isn't re-validating, also provide the cached report. If there is no
10568 // cached report, the Network is still being validated and a report will be sent once
10569 // validation is complete. Note that networks which never undergo validation will still
10570 // have a cached ConnectivityReport with RESULT_SKIPPED.
10571 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10572 try {
10573 cb.onConnectivityReportAvailable(cachedReport);
10574 } catch (RemoteException ex) {
10575 loge("Error invoking onConnectivityReportAvailable", ex);
10576 }
10577 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010578 }
10579 }
10580
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010581 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010582 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10583 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010584 sanitized.setUids(null);
10585 sanitized.setAdministratorUids(new int[0]);
10586 sanitized.setOwnerUid(Process.INVALID_UID);
10587 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010588 }
10589
Cody Kestingf1120be2020-08-03 18:01:40 -070010590 /**
10591 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10592 *
10593 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10594 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010595 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010596 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010597 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010598 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010599 mConnectivityDiagnosticsCallbacks.entrySet()) {
10600 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10601 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010602
James Mattis64b8b0f2020-11-24 17:40:49 -080010603 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010604 if (!nai.satisfies(nri.mRequests.get(0))) {
10605 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010606 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010607
10608 // UID for this callback must either be:
10609 // - INVALID_UID (which sends callbacks to all UIDs), or
10610 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10611 // notified as a result)
10612 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10613 continue;
10614 }
10615
10616 if (!checkConnectivityDiagnosticsPermissions(
10617 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10618 continue;
10619 }
10620
10621 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010622 }
10623 return results;
10624 }
10625
Cody Kesting7474f672021-05-11 14:22:40 -070010626 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10627 @NonNull NetworkAgentInfo nai) {
10628 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10629 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10630 }
10631
Cody Kesting160ef392021-05-05 13:17:22 -070010632 private boolean hasLocationPermission(String packageName, int uid) {
10633 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10634 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10635 // call in a try-catch.
10636 try {
10637 if (!mLocationPermissionChecker.checkLocationPermission(
10638 packageName, null /* featureId */, uid, null /* message */)) {
10639 return false;
10640 }
10641 } catch (SecurityException e) {
10642 return false;
10643 }
10644
10645 return true;
10646 }
10647
10648 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10649 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010650 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010651 && virtual.networkCapabilities.getOwnerUid() == uid
10652 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10653 return true;
10654 }
10655 }
10656
10657 return false;
10658 }
10659
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010660 @VisibleForTesting
10661 boolean checkConnectivityDiagnosticsPermissions(
10662 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10663 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10664 return true;
10665 }
10666
Cody Kesting160ef392021-05-05 13:17:22 -070010667 // Administrator UIDs also contains the Owner UID
10668 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10669 if (!CollectionUtils.contains(administratorUids, callbackUid)
10670 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010671 return false;
10672 }
10673
Cody Kesting7474f672021-05-11 14:22:40 -070010674 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10675 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010676 }
10677
Cody Kestingd199a9d2019-12-17 12:55:28 -080010678 @Override
10679 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010680 @NonNull IConnectivityDiagnosticsCallback callback,
10681 @NonNull NetworkRequest request,
10682 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010683 Objects.requireNonNull(callback, "callback must not be null");
10684 Objects.requireNonNull(request, "request must not be null");
10685 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10686
Cody Kesting73708bf2019-12-18 10:57:50 -080010687 if (request.legacyType != TYPE_NONE) {
10688 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10689 + " Please use NetworkCapabilities instead.");
10690 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010691 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010692 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010693
10694 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10695 // and administrator uids to be safe.
10696 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010697 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010698
10699 final NetworkRequest requestWithId =
10700 new NetworkRequest(
10701 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10702
10703 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10704 //
10705 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10706 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10707 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010708 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010709 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010710 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010711
10712 mConnectivityDiagnosticsHandler.sendMessage(
10713 mConnectivityDiagnosticsHandler.obtainMessage(
10714 ConnectivityDiagnosticsHandler
10715 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10716 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010717 }
10718
10719 @Override
10720 public void unregisterConnectivityDiagnosticsCallback(
10721 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010722 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010723 mConnectivityDiagnosticsHandler.sendMessage(
10724 mConnectivityDiagnosticsHandler.obtainMessage(
10725 ConnectivityDiagnosticsHandler
10726 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010727 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010728 0,
10729 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010730 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010731
10732 @Override
10733 public void simulateDataStall(int detectionMethod, long timestampMillis,
10734 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010735 Objects.requireNonNull(network, "network must not be null");
10736 Objects.requireNonNull(extras, "extras must not be null");
10737
paulhu3ffffe72021-09-16 10:15:22 +080010738 enforceAnyPermissionOf(mContext,
10739 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010740 android.Manifest.permission.NETWORK_STACK);
10741 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10742 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010743 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010744 }
10745
10746 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010747 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010748 throw new SecurityException("Data Stall simulation is only possible for network "
10749 + "creators");
10750 }
10751
Cody Kesting652e3ec2020-05-21 12:08:21 -070010752 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10753 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10754 // Data Stall information as a DataStallReportParcelable and passing to
10755 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10756 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010757 final DataStallReportParcelable p = new DataStallReportParcelable();
10758 p.timestampMillis = timestampMillis;
10759 p.detectionMethod = detectionMethod;
10760
10761 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10762 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10763 }
10764 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10765 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10766 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10767 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10768 }
10769
Serik Beketayevec8ad212020-12-07 22:43:07 -080010770 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010771 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010772
lucaslin66f44212021-02-23 01:12:55 +080010773 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10774 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010775 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010776 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010777 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010778 }
lucaslin37a16d92021-01-21 19:48:09 +080010779
10780 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010781 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010782 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010783 nai.clatd.interfaceLinkStateChanged(iface, up);
10784 }
10785 }
10786
10787 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010788 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010789 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010790 nai.clatd.interfaceRemoved(iface);
10791 }
lucaslin66f44212021-02-23 01:12:55 +080010792 }
10793 }
10794
lucaslin1a8b4c62021-01-21 02:02:55 +080010795 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10796
10797 /**
10798 * Class used for updating network activity tracking with netd and notify network activity
10799 * changes.
10800 */
10801 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010802 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010803 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010804 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010805 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10806 new RemoteCallbackList<>();
10807 // Indicate the current system default network activity is active or not.
10808 @GuardedBy("mActiveIdleTimers")
10809 private boolean mNetworkActive;
10810 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010811 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010812 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010813
Chalard Jean46bfbf02022-02-02 00:56:25 +090010814 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010815 public final int timeout;
10816 public final int transportType;
10817
10818 IdleTimerParams(int timeout, int transport) {
10819 this.timeout = timeout;
10820 this.transportType = transport;
10821 }
10822 }
10823
10824 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010825 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010826 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010827 mNetd = netd;
10828 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010829 }
10830
lucaslin66f44212021-02-23 01:12:55 +080010831 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10832 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10833 synchronized (mActiveIdleTimers) {
10834 mNetworkActive = active;
10835 // If there are no idle timers, it means that system is not monitoring
10836 // activity, so the system default network for those default network
10837 // unspecified apps is always considered active.
10838 //
10839 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10840 // any network activity change event. Whenever this event is received,
10841 // the mActiveIdleTimers should be always not empty. The legacy behavior
10842 // is no-op. Remove to refer to mNetworkActive only.
10843 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10844 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10845 }
10846 }
10847 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010848
lucaslin1193a5d2021-01-21 02:04:15 +080010849 // The network activity should only be updated from ConnectivityService handler thread
10850 // when mActiveIdleTimers lock is held.
10851 @GuardedBy("mActiveIdleTimers")
10852 private void reportNetworkActive() {
10853 final int length = mNetworkActivityListeners.beginBroadcast();
10854 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10855 try {
10856 for (int i = 0; i < length; i++) {
10857 try {
10858 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10859 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010860 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010861 }
10862 }
10863 } finally {
10864 mNetworkActivityListeners.finishBroadcast();
10865 }
10866 }
10867
10868 @GuardedBy("mActiveIdleTimers")
10869 public void handleReportNetworkActivity() {
10870 synchronized (mActiveIdleTimers) {
10871 reportNetworkActive();
10872 }
10873 }
10874
lucaslin1a8b4c62021-01-21 02:02:55 +080010875 // This is deprecated and only to support legacy use cases.
10876 private int transportTypeToLegacyType(int type) {
10877 switch (type) {
10878 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010879 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010880 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010881 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010882 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010883 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010884 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010885 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010886 default:
10887 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10888 }
10889 return ConnectivityManager.TYPE_NONE;
10890 }
10891
10892 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10893 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10894 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10895 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10896 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10897 final long ident = Binder.clearCallingIdentity();
10898 try {
10899 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10900 RECEIVE_DATA_ACTIVITY_CHANGE,
10901 null /* resultReceiver */,
10902 null /* scheduler */,
10903 0 /* initialCode */,
10904 null /* initialData */,
10905 null /* initialExtra */);
10906 } finally {
10907 Binder.restoreCallingIdentity(ident);
10908 }
10909 }
10910
10911 /**
10912 * Setup data activity tracking for the given network.
10913 *
10914 * Every {@code setupDataActivityTracking} should be paired with a
10915 * {@link #removeDataActivityTracking} for cleanup.
10916 */
10917 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10918 final String iface = networkAgent.linkProperties.getInterfaceName();
10919
10920 final int timeout;
10921 final int type;
10922
10923 if (networkAgent.networkCapabilities.hasTransport(
10924 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10925 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010926 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010927 10);
10928 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10929 } else if (networkAgent.networkCapabilities.hasTransport(
10930 NetworkCapabilities.TRANSPORT_WIFI)) {
10931 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010932 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010933 15);
10934 type = NetworkCapabilities.TRANSPORT_WIFI;
10935 } else {
10936 return; // do not track any other networks
10937 }
10938
lucaslinb961efc2021-01-21 02:03:17 +080010939 updateRadioPowerState(true /* isActive */, type);
10940
lucaslin1a8b4c62021-01-21 02:02:55 +080010941 if (timeout > 0 && iface != null) {
10942 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010943 synchronized (mActiveIdleTimers) {
10944 // Networks start up.
10945 mNetworkActive = true;
10946 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10947 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10948 reportNetworkActive();
10949 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010950 } catch (Exception e) {
10951 // You shall not crash!
10952 loge("Exception in setupDataActivityTracking " + e);
10953 }
10954 }
10955 }
10956
10957 /**
10958 * Remove data activity tracking when network disconnects.
10959 */
10960 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10961 final String iface = networkAgent.linkProperties.getInterfaceName();
10962 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10963
lucaslinb961efc2021-01-21 02:03:17 +080010964 if (iface == null) return;
10965
10966 final int type;
10967 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10968 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10969 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10970 type = NetworkCapabilities.TRANSPORT_WIFI;
10971 } else {
10972 return; // do not track any other networks
10973 }
10974
10975 try {
10976 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010977 synchronized (mActiveIdleTimers) {
10978 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10979 // The call fails silently if no idle timer setup for this interface
10980 mNetd.idletimerRemoveInterface(iface, params.timeout,
10981 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010982 }
lucaslinb961efc2021-01-21 02:03:17 +080010983 } catch (Exception e) {
10984 // You shall not crash!
10985 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010986 }
10987 }
10988
10989 /**
10990 * Update data activity tracking when network state is updated.
10991 */
10992 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10993 NetworkAgentInfo oldNetwork) {
10994 if (newNetwork != null) {
10995 setupDataActivityTracking(newNetwork);
10996 }
10997 if (oldNetwork != null) {
10998 removeDataActivityTracking(oldNetwork);
10999 }
11000 }
lucaslinb961efc2021-01-21 02:03:17 +080011001
11002 private void updateRadioPowerState(boolean isActive, int transportType) {
11003 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11004 switch (transportType) {
11005 case NetworkCapabilities.TRANSPORT_CELLULAR:
11006 bs.reportMobileRadioPowerState(isActive, NO_UID);
11007 break;
11008 case NetworkCapabilities.TRANSPORT_WIFI:
11009 bs.reportWifiRadioPowerState(isActive, NO_UID);
11010 break;
11011 default:
11012 logw("Untracked transport type:" + transportType);
11013 }
11014 }
lucaslin1193a5d2021-01-21 02:04:15 +080011015
11016 public boolean isDefaultNetworkActive() {
11017 synchronized (mActiveIdleTimers) {
11018 // If there are no idle timers, it means that system is not monitoring activity,
11019 // so the default network is always considered active.
11020 //
11021 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
11022 // tracking is disabled (negative idle timer value configured), or no active default
11023 // network. In the latter case, this reports active but it should report inactive.
11024 return mNetworkActive || mActiveIdleTimers.isEmpty();
11025 }
11026 }
11027
11028 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11029 mNetworkActivityListeners.register(l);
11030 }
11031
11032 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11033 mNetworkActivityListeners.unregister(l);
11034 }
lucaslin012f7a12021-01-21 02:04:35 +080011035
11036 public void dump(IndentingPrintWriter pw) {
11037 synchronized (mActiveIdleTimers) {
11038 pw.print("mNetworkActive="); pw.println(mNetworkActive);
11039 pw.println("Idle timers:");
11040 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
11041 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11042 final IdleTimerParams params = ent.getValue();
11043 pw.print(" timeout="); pw.print(params.timeout);
11044 pw.print(" type="); pw.println(params.transportType);
11045 }
11046 }
11047 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011048 }
James Mattis47db0582021-01-01 14:13:35 -080011049
Daniel Brightf9e945b2020-06-15 16:10:01 -070011050 /**
11051 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11052 *
11053 * @param socketInfo the socket information
11054 * @param callback the callback to register
11055 */
11056 @Override
11057 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11058 @NonNull final IQosCallback callback) {
11059 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11060 if (nai == null || nai.networkCapabilities == null) {
11061 try {
11062 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11063 } catch (final RemoteException ex) {
11064 loge("registerQosCallbackInternal: RemoteException", ex);
11065 }
11066 return;
11067 }
11068 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11069 }
11070
11071 /**
11072 * Register a {@link IQosCallback} with base {@link QosFilter}.
11073 *
11074 * @param filter the filter to register
11075 * @param callback the callback to register
11076 * @param nai the agent information related to the filter's network
11077 */
11078 @VisibleForTesting
11079 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11080 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011081 Objects.requireNonNull(filter, "filter must be non-null");
11082 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011083
11084 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011085 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11086 // on this network is unregistered when the app loses permission or b) no QoS
11087 // callbacks are sent for restricted networks unless the app currently has permission
11088 // to access restricted networks.
11089 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011090 }
11091 mQosCallbackTracker.registerCallback(callback, filter, nai);
11092 }
11093
11094 /**
11095 * Unregisters the given callback.
11096 *
11097 * @param callback the callback to unregister
11098 */
11099 @Override
11100 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011101 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011102 mQosCallbackTracker.unregisterCallback(callback);
11103 }
James Mattis47db0582021-01-01 14:13:35 -080011104
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011105 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11106 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11107 // Enterprise device can be fully managed like device owner and such use case
11108 // also should be supported. Calling app check for work profile and fully managed device
11109 // is already done in DevicePolicyManager.
11110 // This check is an extra caution to be sure device is fully managed or not.
11111 final UserManager um = mContext.getSystemService(UserManager.class);
11112 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11113 if (um.isManagedProfile(profile.getIdentifier())) {
11114 return true;
11115 }
11116 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
11117 return false;
11118 }
11119
James Mattis45d81842021-01-10 14:24:24 -080011120 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011121 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011122 *
11123 * See the documentation for the individual preferences for a description of the supported
11124 * behaviors.
11125 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011126 * @param profile If the device owner is set, any profile is allowed.
11127 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011128 * @param preferences the list of profile network preferences for the
11129 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011130 * @param listener an optional listener to listen for completion of the operation.
11131 */
11132 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011133 public void setProfileNetworkPreferences(
11134 @NonNull final UserHandle profile,
11135 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011136 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011137 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011138 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011139
11140 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011141 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11142 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11143 .build();
11144 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011145 }
11146
paulhu3ffffe72021-09-16 10:15:22 +080011147 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011148 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011149 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011150 }
11151 if (profile.getIdentifier() < 0) {
11152 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11153 + "UserHandle.CURRENT not supported)");
11154 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011155 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11156 throw new IllegalArgumentException("Profile must be a managed profile "
11157 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011158 }
paulhuaa0743d2021-05-26 21:56:03 +080011159
Chalard Jean0606fc82022-12-14 20:34:43 +090011160 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011161 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011162 for (final ProfileNetworkPreference preference : preferences) {
11163 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011164 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011165 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011166 switch (preference.getPreference()) {
11167 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11168 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011169 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011170 if (preference.getPreferenceEnterpriseId() != 0) {
11171 throw new IllegalArgumentException(
11172 "Invalid enterprise identifier in setProfileNetworkPreferences");
11173 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011174 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011175 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11176 blockingNonEnterprise = true;
11177 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011178 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11179 allowFallback = false;
11180 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011181 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011182 // This code is needed even though there is a check later on,
11183 // because isRangeAlreadyInPreferenceList assumes that every preference
11184 // has a UID list.
11185 if (hasDefaultPreference) {
11186 throw new IllegalArgumentException(
11187 "Default profile preference should not be set along with other "
11188 + "preference");
11189 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011190 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11191 throw new IllegalArgumentException(
11192 "Invalid enterprise identifier in setProfileNetworkPreferences");
11193 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011194 final Set<UidRange> uidRangeSet =
11195 getUidListToBeAppliedForNetworkPreference(profile, preference);
11196 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11197 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11198 } else {
11199 throw new IllegalArgumentException(
11200 "Overlapping uid range in setProfileNetworkPreferences");
11201 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011202 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011203 nc.addEnterpriseId(
11204 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011205 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11206 break;
11207 default:
11208 throw new IllegalArgumentException(
11209 "Invalid preference in setProfileNetworkPreferences");
11210 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011211 preferenceList.add(new ProfileNetworkPreferenceInfo(
11212 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011213 if (hasDefaultPreference && preferenceList.size() > 1) {
11214 throw new IllegalArgumentException(
11215 "Default profile preference should not be set along with other preference");
11216 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011217 }
11218 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011219 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011220 }
11221
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011222 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11223 @NonNull final UserHandle profile,
11224 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11225 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011226 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11227 profileNetworkPreference.getIncludedUids());
11228
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011229 if (uidRangeSet.size() > 0) {
11230 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11231 throw new IllegalArgumentException(
11232 "Allow uid range is outside the uid range of profile.");
11233 }
11234 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011235 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011236 profileNetworkPreference.getExcludedUids());
11237 if (disallowUidRangeSet.size() > 0) {
11238 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11239 throw new IllegalArgumentException(
11240 "disallow uid range is outside the uid range of profile.");
11241 }
11242 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11243 disallowUidRangeSet);
11244 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011245 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011246 uidRangeSet.add(profileUids);
11247 }
11248 }
11249 return uidRangeSet;
11250 }
11251
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011252 private boolean isEnterpriseIdentifierValid(
11253 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011254 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011255 return true;
11256 }
11257 return false;
11258 }
11259
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011260 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011261 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011262 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011263 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011264 // The NRI for a user should contain the request for capabilities.
11265 // If fallback to default network is needed then NRI should include
11266 // the request for the default network. Create an image of it to
11267 // have the correct UIDs in it (also a request can only be part of one NRI, because
11268 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011269 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11270 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011271 if (pref.allowFallback) {
11272 nrs.add(createDefaultInternetRequestForTransport(
11273 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11274 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011275 if (VDBG) {
11276 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11277 pref.capabilities.getUids()));
11278 }
11279
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011280 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011281 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011282 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011283 result.add(nri);
11284 }
11285 return result;
11286 }
11287
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011288 /**
11289 * Compare if the given UID range sets have the same UIDs.
11290 *
11291 */
11292 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011293 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011294 @NonNull Set<UidRange> uidRangeSet) {
11295 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11296 return false;
11297 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011298 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011299 if (UidRangeUtils.doesRangeSetOverlap(
11300 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11301 return true;
11302 }
11303 }
11304 return false;
11305 }
11306
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011307 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011308 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011309 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011310 /*
11311 * handleSetProfileNetworkPreference is always called for single user.
11312 * preferenceList only contains preferences for different uids within the same user
11313 * (enforced by getUidListToBeAppliedForNetworkPreference).
11314 * Clear all the existing preferences for the user before applying new preferences.
11315 *
11316 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011317 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11318 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011319 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11320 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011321
paulhu74128522021-09-28 02:29:03 +000011322 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11323 addPerAppDefaultNetworkRequests(
11324 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011325 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011326
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011327 // Finally, rematch.
11328 rematchAllNetworksAndRequests();
11329
11330 if (null != listener) {
11331 try {
11332 listener.onComplete();
11333 } catch (RemoteException e) {
11334 loge("Listener for setProfileNetworkPreference has died");
11335 }
11336 }
11337 }
11338
paulhu51f77dc2021-06-07 02:34:20 +000011339 @VisibleForTesting
11340 @NonNull
11341 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11342 @NonNull final Set<Integer> uids) {
11343 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11344 if (uids.size() == 0) {
11345 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11346 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11347 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11348 return nris;
11349 }
11350
11351 final List<NetworkRequest> requests = new ArrayList<>();
11352 // The NRI should be comprised of two layers:
11353 // - The request for the mobile network preferred.
11354 // - The request for the default network, for fallback.
11355 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011356 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011357 requests.add(createDefaultInternetRequestForTransport(
11358 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11359 final Set<UidRange> ranges = new ArraySet<>();
11360 for (final int uid : uids) {
11361 ranges.add(new UidRange(uid, uid));
11362 }
11363 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011364 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011365 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011366 return nris;
11367 }
11368
11369 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011370 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011371 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11372 addPerAppDefaultNetworkRequests(
11373 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011374 // Finally, rematch.
11375 rematchAllNetworksAndRequests();
11376 }
11377
Patrick Rohr2857ac42022-01-21 14:58:16 +010011378 private void handleIngressRateLimitChanged() {
11379 final long oldIngressRateLimit = mIngressRateLimit;
11380 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11381 mContext);
11382 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11383 if (canNetworkBeRateLimited(networkAgent)) {
11384 // If rate limit has previously been enabled, remove the old limit first.
11385 if (oldIngressRateLimit >= 0) {
11386 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11387 }
11388 if (mIngressRateLimit >= 0) {
11389 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11390 mIngressRateLimit);
11391 }
11392 }
11393 }
11394 }
11395
11396 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011397 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
11398 if (!SdkLevel.isAtLeastT()) return false;
11399
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011400 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11401 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11402 // internet connectivity can be rate limited.
11403 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11404 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011405 return false;
11406 }
11407
11408 final String iface = networkAgent.linkProperties.getInterfaceName();
11409 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011410 // This may happen in tests, but if there is no interface then there is nothing that
11411 // can be rate limited.
11412 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011413 return false;
11414 }
11415 return true;
11416 }
11417
James Mattis45d81842021-01-10 14:24:24 -080011418 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011419 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11420 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011421 }
11422
11423 /**
11424 * Used by automotive devices to set the network preferences used to direct traffic at an
11425 * application level as per the given OemNetworkPreferences. An example use-case would be an
11426 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11427 * vehicle via a particular network.
11428 *
11429 * Calling this will overwrite the existing preference.
11430 *
James Mattisda32cfe2021-01-26 16:23:52 -080011431 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011432 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011433 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011434 */
James Mattis47db0582021-01-01 14:13:35 -080011435 @Override
James Mattis45d81842021-01-10 14:24:24 -080011436 public void setOemNetworkPreference(
11437 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011438 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011439
James Mattisfa270db2021-05-31 17:11:10 -070011440 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11441 // Only bypass the permission/device checks if this is a valid test request.
11442 if (isValidTestOemNetworkPreference(preference)) {
11443 enforceManageTestNetworksPermission();
11444 } else {
11445 enforceAutomotiveDevice();
11446 enforceOemNetworkPreferencesPermission();
11447 validateOemNetworkPreferences(preference);
11448 }
James Mattis45d81842021-01-10 14:24:24 -080011449
James Mattis45d81842021-01-10 14:24:24 -080011450 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11451 new Pair<>(preference, listener)));
11452 }
11453
James Mattisfa270db2021-05-31 17:11:10 -070011454 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011455 * Sets the specified UIDs to get/receive the VPN as the only default network.
11456 *
11457 * Calling this will overwrite the existing network preference for this session, and the
11458 * specified UIDs won't get any default network when no VPN is connected.
11459 *
11460 * @param session The VPN session which manages the passed UIDs.
11461 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11462 * setting for this session if the array is empty. Null is not allowed, the
11463 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11464 * @hide
11465 */
11466 @Override
11467 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11468 Objects.requireNonNull(ranges);
11469 enforceNetworkStackOrSettingsPermission();
11470 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11471 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11472 throw new IllegalArgumentException(
11473 "setVpnNetworkPreference: Passed UID ranges overlap");
11474 }
11475
11476 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11477 new VpnNetworkPreferenceInfo(session,
11478 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11479 }
11480
11481 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11482 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11483
11484 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11485 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11486
11487 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11488 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11489 // Finally, rematch.
11490 rematchAllNetworksAndRequests();
11491 }
11492
11493 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11494 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11495 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11496 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11497 final List<NetworkRequest> requests = new ArrayList<>();
11498 // Request VPN only, so other networks won't be the fallback options when VPN is not
11499 // connected temporarily.
11500 requests.add(createVpnRequest());
11501 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11502 setNetworkRequestUids(requests, uidRanges);
11503 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11504 }
11505 return nris;
11506 }
11507
11508 /**
James Mattisfa270db2021-05-31 17:11:10 -070011509 * Check the validity of an OEM network preference to be used for testing purposes.
11510 * @param preference the preference to validate
11511 * @return true if this is a valid OEM network preference test request.
11512 */
11513 private boolean isValidTestOemNetworkPreference(
11514 @NonNull final OemNetworkPreferences preference) {
11515 // Allow for clearing of an existing OemNetworkPreference used for testing.
11516 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11517 // changes after this check is complete. This is an unlikely scenario as calling of this API
11518 // is controlled by the OEM therefore the added complexity is not worth adding given those
11519 // circumstances. That said, it is an edge case to be aware of hence this comment.
11520 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11521 && isTestOemNetworkPreference(mOemNetworkPreferences);
11522 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11523 }
11524
11525 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11526 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11527 return prefMap.size() == 1
11528 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11529 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11530 }
11531
James Mattis45d81842021-01-10 14:24:24 -080011532 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11533 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11534 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011535 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11536 throw new IllegalArgumentException(
11537 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11538 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011539 }
11540 }
11541 }
11542
11543 private void handleSetOemNetworkPreference(
11544 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011545 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011546 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11547 if (DBG) {
11548 log("set OEM network preferences :" + preference.toString());
11549 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011550
James Mattiscb1e0362021-04-06 17:07:42 -070011551 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011552 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11553 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11554 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011555 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011556
11557 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011558 try {
11559 listener.onComplete();
11560 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011561 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011562 }
James Mattis45d81842021-01-10 14:24:24 -080011563 }
11564 }
11565
paulhu74128522021-09-28 02:29:03 +000011566 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011567 // Skip the requests which are set by other network preference. Because the uid range rules
11568 // should stay in netd.
11569 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011570 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011571 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011572 }
11573
James Mattis3ce3d3c2021-02-09 18:18:28 -080011574 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11575 ensureRunningOnConnectivityServiceThread();
11576 mDefaultNetworkRequests.addAll(nris);
11577 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11578 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011579 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011580 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11581 nrisToRegister.addAll(
11582 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11583 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011584 }
11585
11586 /**
11587 * All current requests that are tracking the default network need to be assessed as to whether
11588 * or not the current set of per-application default requests will be changing their default
11589 * network. If so, those requests will need to be updated so that they will send callbacks for
11590 * default network changes at the appropriate time. Additionally, those requests tracking the
11591 * default that were previously updated by this flow will need to be reassessed.
11592 * @return the nris which will need to be updated.
11593 */
11594 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11595 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11596 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11597 // same nri in the map's values for each of its NetworkRequest objects.
11598 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011599 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011600 // Include this nri if it is currently being tracked.
11601 if (isPerAppTrackedNri(nri)) {
11602 defaultCallbackRequests.add(nri);
11603 continue;
11604 }
11605 // We only track callbacks for requests tracking the default.
11606 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11607 continue;
11608 }
11609 // Include this nri if it will be tracked by the new per-app default requests.
11610 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011611 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011612 if (isNriGoingToBeTracked) {
11613 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011614 }
11615 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011616 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011617 }
11618
James Mattis3ce3d3c2021-02-09 18:18:28 -080011619 /**
11620 * Create nris for those network requests that are currently tracking the default network that
11621 * are being controlled by a per-application default.
11622 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11623 * foundation when creating the nri. Important items include the calling uid's original
11624 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11625 * requests are assumed to have already been validated as needing to be updated.
11626 * @return the Set of nris to use when registering network requests.
11627 */
11628 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11629 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11630 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11631 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11632 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011633 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011634
Chalard Jean9473c982021-07-29 20:03:04 +090011635 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011636 if (trackingNri == mDefaultRequest) {
11637 callbackRequestsToRegister.add(new NetworkRequestInfo(
11638 callbackRequest,
11639 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11640 continue;
11641 }
11642
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011643 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011644 callbackRequestsToRegister.add(new NetworkRequestInfo(
11645 callbackRequest,
11646 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011647 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011648 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011649 }
11650 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011651 }
11652
Chalard Jean17215832021-03-01 14:06:28 +090011653 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11654 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011655 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011656 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011657 }
11658 }
11659
James Mattis45d81842021-01-10 14:24:24 -080011660 /**
11661 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11662 */
11663 @VisibleForTesting
11664 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011665 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011666 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011667 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011668 final SparseArray<Set<Integer>> uids =
11669 createUidsFromOemNetworkPreferences(preference);
11670 for (int i = 0; i < uids.size(); i++) {
11671 final int key = uids.keyAt(i);
11672 final Set<Integer> value = uids.valueAt(i);
11673 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11674 // No need to add an nri without any requests.
11675 if (0 == nri.mRequests.size()) {
11676 continue;
11677 }
11678 nris.add(nri);
11679 }
11680
11681 return nris;
11682 }
11683
11684 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11685 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011686 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011687 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011688 final List<UserHandle> users =
11689 mContext.getSystemService(UserManager.class).getUserHandles(true);
11690 if (null == users || users.size() == 0) {
11691 if (VDBG || DDBG) {
11692 log("No users currently available for setting the OEM network preference.");
11693 }
James Mattisb6b6a432021-06-01 22:30:36 -070011694 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011695 }
James Mattis45d81842021-01-10 14:24:24 -080011696 for (final Map.Entry<String, Integer> entry :
11697 preference.getNetworkPreferences().entrySet()) {
11698 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011699 // Add the rules for all users as this policy is device wide.
11700 for (final UserHandle user : users) {
11701 try {
11702 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11703 if (!prefToUids.contains(pref)) {
11704 prefToUids.put(pref, new ArraySet<>());
11705 }
11706 prefToUids.get(pref).add(uid);
11707 } catch (PackageManager.NameNotFoundException e) {
11708 // Although this may seem like an error scenario, it is ok that uninstalled
11709 // packages are sent on a network preference as the system will watch for
11710 // package installations associated with this network preference and update
11711 // accordingly. This is done to minimize race conditions on app install.
11712 continue;
James Mattis45d81842021-01-10 14:24:24 -080011713 }
James Mattis45d81842021-01-10 14:24:24 -080011714 }
11715 }
James Mattisb6b6a432021-06-01 22:30:36 -070011716 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011717 }
11718
11719 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11720 @OemNetworkPreferences.OemNetworkPreference final int preference,
11721 @NonNull final Set<Integer> uids) {
11722 final List<NetworkRequest> requests = new ArrayList<>();
11723 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11724 switch (preference) {
11725 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11726 requests.add(createUnmeteredNetworkRequest());
11727 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011728 requests.add(createDefaultInternetRequestForTransport(
11729 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011730 break;
11731 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11732 requests.add(createUnmeteredNetworkRequest());
11733 requests.add(createOemPaidNetworkRequest());
11734 break;
11735 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11736 requests.add(createOemPaidNetworkRequest());
11737 break;
11738 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11739 requests.add(createOemPrivateNetworkRequest());
11740 break;
James Mattisfa270db2021-05-31 17:11:10 -070011741 case OEM_NETWORK_PREFERENCE_TEST:
11742 requests.add(createUnmeteredNetworkRequest());
11743 requests.add(createTestNetworkRequest());
11744 requests.add(createDefaultRequest());
11745 break;
11746 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11747 requests.add(createTestNetworkRequest());
11748 break;
James Mattis45d81842021-01-10 14:24:24 -080011749 default:
11750 // This should never happen.
11751 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11752 + " called with invalid preference of " + preference);
11753 }
11754
James Mattisfa270db2021-05-31 17:11:10 -070011755 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011756 for (final int uid : uids) {
11757 ranges.add(new UidRange(uid, uid));
11758 }
11759 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011760 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011761 }
11762
11763 private NetworkRequest createUnmeteredNetworkRequest() {
11764 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11765 .addCapability(NET_CAPABILITY_NOT_METERED)
11766 .addCapability(NET_CAPABILITY_VALIDATED);
11767 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11768 }
11769
11770 private NetworkRequest createOemPaidNetworkRequest() {
11771 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11772 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11773 .addCapability(NET_CAPABILITY_OEM_PAID)
11774 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11775 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11776 }
11777
11778 private NetworkRequest createOemPrivateNetworkRequest() {
11779 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11780 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11781 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11782 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11783 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11784 }
11785
11786 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011787 final NetworkCapabilities netcap = new NetworkCapabilities();
11788 netcap.addCapability(NET_CAPABILITY_INTERNET);
11789 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11790 return netcap;
11791 }
11792
11793 private NetworkRequest createTestNetworkRequest() {
11794 final NetworkCapabilities netcap = new NetworkCapabilities();
11795 netcap.clearAll();
11796 netcap.addTransportType(TRANSPORT_TEST);
11797 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011798 }
James Mattis47db0582021-01-01 14:13:35 -080011799 }
markchien738ad912021-12-09 18:15:45 +080011800
11801 @Override
11802 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11803 enforceNetworkStackOrSettingsPermission();
11804
11805 try {
11806 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011807 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011808 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011809 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011810 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011811 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011812 throw new IllegalStateException(e);
11813 }
11814 }
11815
11816 @Override
11817 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11818 enforceNetworkStackOrSettingsPermission();
11819
11820 try {
11821 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011822 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011823 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011824 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011825 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011826 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011827 throw new IllegalStateException(e);
11828 }
11829 }
markchiene1561fa2021-12-09 22:00:56 +080011830
11831 @Override
markchien3c04e662022-03-22 16:29:56 +080011832 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011833 enforceNetworkStackOrSettingsPermission();
11834
markchien3c04e662022-03-22 16:29:56 +080011835 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11836 int firewallRule = getFirewallRuleType(chain, rule);
11837
11838 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11839 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11840 }
11841
markchiene1561fa2021-12-09 22:00:56 +080011842 try {
markchien3c04e662022-03-22 16:29:56 +080011843 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011844 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011845 throw new IllegalStateException(e);
11846 }
11847 }
markchien98a6f952022-01-13 23:43:53 +080011848
Motomu Utsumi900b8062023-01-19 16:16:49 +090011849 @Override
11850 public int getUidFirewallRule(final int chain, final int uid) {
11851 enforceNetworkStackOrSettingsPermission();
11852 return mBpfNetMaps.getUidRule(chain, uid);
11853 }
11854
markchien3c04e662022-03-22 16:29:56 +080011855 private int getFirewallRuleType(int chain, int rule) {
11856 final int defaultRule;
11857 switch (chain) {
11858 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011859 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11860 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011861 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011862 defaultRule = FIREWALL_RULE_ALLOW;
11863 break;
11864 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11865 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11866 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11867 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11868 defaultRule = FIREWALL_RULE_DENY;
11869 break;
11870 default:
11871 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11872 }
11873 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11874
11875 return rule;
11876 }
11877
markchien98a6f952022-01-13 23:43:53 +080011878 @Override
11879 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11880 enforceNetworkStackOrSettingsPermission();
11881
11882 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011883 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011884 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011885 throw new IllegalStateException(e);
11886 }
11887 }
11888
markchien00a0bed2022-01-13 23:46:13 +080011889 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011890 public boolean getFirewallChainEnabled(final int chain) {
11891 enforceNetworkStackOrSettingsPermission();
11892
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011893 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011894 }
11895
11896 @Override
markchien00a0bed2022-01-13 23:46:13 +080011897 public void replaceFirewallChain(final int chain, final int[] uids) {
11898 enforceNetworkStackOrSettingsPermission();
11899
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011900 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011901 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080011902
11903 @Override
11904 public IBinder getCompanionDeviceManagerProxyService() {
11905 enforceNetworkStackPermission(mContext);
11906 return mCdmps;
11907 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011908}