blob: d47099115832e7968362680604ccc071bda1578d [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;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
Chalard Jeane0aaca52023-10-17 13:23:07 +090022import static android.content.pm.PackageManager.FEATURE_LEANBACK;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090023import static android.content.pm.PackageManager.FEATURE_WATCH;
24import static android.content.pm.PackageManager.FEATURE_WIFI;
25import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090026import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Motomu Utsumi11d33452024-04-02 18:29:08 +090027import static android.net.BpfNetMapsConstants.METERED_ALLOW_CHAINS;
28import static android.net.BpfNetMapsConstants.METERED_DENY_CHAINS;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090029import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
30import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
31import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
34import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
35import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
36import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Junyu Lai38c75032023-12-04 07:52:19 +000037import static android.net.ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090038import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
Motomu Utsumiff555a72024-05-23 23:22:40 +090039import static android.net.ConnectivityManager.BLOCKED_REASON_APP_BACKGROUND;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090040import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Motomu Utsumicfd5a512024-05-27 02:12:43 +000041import static android.net.ConnectivityManager.BLOCKED_REASON_NETWORK_RESTRICTED;
Remi NGUYEN VAN42dc6e42024-07-17 10:45:38 +090042import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090043import static android.net.ConnectivityManager.CALLBACK_AVAILABLE;
44import static android.net.ConnectivityManager.CALLBACK_BLK_CHANGED;
45import static android.net.ConnectivityManager.CALLBACK_CAP_CHANGED;
Aaron Huang9fe47be2021-06-08 13:11:45 +080046import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090047import static android.net.ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED;
48import static android.net.ConnectivityManager.CALLBACK_LOSING;
49import static android.net.ConnectivityManager.CALLBACK_LOST;
50import static android.net.ConnectivityManager.CALLBACK_PRECHECK;
Patrick Rohr93136f12024-12-02 15:46:48 -080051import static android.net.ConnectivityManager.CALLBACK_RESERVED;
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090052import static android.net.ConnectivityManager.CALLBACK_RESUMED;
53import static android.net.ConnectivityManager.CALLBACK_SUSPENDED;
54import static android.net.ConnectivityManager.CALLBACK_UNAVAIL;
Jeff Sharkey971cd162011-08-29 16:02:57 -070055import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Suprabh Shukla22ea1662024-02-08 16:06:01 -080056import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
markchien3c04e662022-03-22 16:29:56 +080057import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
58import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
59import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +090060import static android.net.ConnectivityManager.NETID_UNSET;
Remi NGUYEN VAN42dc6e42024-07-17 10:45:38 +090061import static android.net.ConnectivityManager.NetworkCallback.DECLARED_METHODS_ALL;
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +090062import static android.net.ConnectivityManager.NetworkCallback.DECLARED_METHODS_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090063import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090064import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090065import static android.net.ConnectivityManager.TYPE_MOBILE;
66import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
67import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
68import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
69import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
70import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
71import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
72import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
73import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
74import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070075import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090076import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070077import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090078import static android.net.ConnectivityManager.TYPE_WIFI;
79import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070080import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070081import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080082import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
Motomu Utsumi0b4be792024-05-07 15:51:52 +090083import static android.net.INetd.PERMISSION_INTERNET;
lucasline117e2e2019-10-22 18:27:33 +080084import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080085import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070086import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080087import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Yang Sunca537d52024-01-19 12:53:50 +080088import static android.net.MulticastRoutingConfig.FORWARD_NONE;
Paul Jensen53f08952015-06-16 14:27:36 -040089import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090090import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090091import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090092import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090093import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Motomu Utsumiab750ab2024-05-31 18:15:07 +090094import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090095import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090096import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
97import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060098import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090099import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +0800100import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +0900101import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -0800102import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
103import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +0800104import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900105import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +0900106import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -0800107import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
108import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -0800109import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
110import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
111import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Patrick Rohre7a4b082024-12-17 19:02:11 -0800112import static android.net.NetworkCapabilities.RES_ID_MATCH_ALL_RESERVATIONS;
Sarup Dalwani18b72622025-02-08 04:06:44 +0000113import static android.net.NetworkCapabilities.RES_ID_UNSET;
Chalard Jeand61375d2020-01-14 22:46:36 +0900114import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +0900115import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Chalard Jean324365a2025-03-21 10:12:38 +0900116import static android.net.NetworkCapabilities.TRANSPORT_THREAD;
Jeff Sharkey07e19362017-10-27 17:22:59 -0600117import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -0700118import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +0800119import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +0900120import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -0700121import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
122import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Motomu Utsumiad480e02024-01-30 16:21:51 +0900123import static android.net.connectivity.ConnectivityCompatChanges.ENABLE_MATCH_LOCAL_NETWORK;
Junyu Lai0b806fd2025-03-19 07:30:11 +0800124import static android.net.connectivity.ConnectivityCompatChanges.ENABLE_MATCH_NON_THREAD_LOCAL_NETWORKS;
Motomu Utsumiad480e02024-01-30 16:21:51 +0900125import static android.net.connectivity.ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION;
Motomu Utsumib15be222024-05-15 18:50:08 +0900126import static android.net.connectivity.ConnectivityCompatChanges.NETWORK_BLOCKED_WITHOUT_INTERNET_PERMISSION;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700127import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +0800128import static android.os.Process.VPN_UID;
Patrick Rohr7d6dfd52024-12-05 04:06:53 +0000129import static android.system.OsConstants.ENOENT;
130import static android.system.OsConstants.ENOTCONN;
131import static android.system.OsConstants.EOPNOTSUPP;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100132import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700133import static android.system.OsConstants.IPPROTO_TCP;
134import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900135
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700136import static com.android.net.module.util.BpfUtils.BPF_CGROUP_GETSOCKOPT;
Junyu Lai155760b2023-10-05 14:51:00 +0800137import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700138import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_CONNECT;
Junyu Lai155760b2023-10-05 14:51:00 +0800139import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700140import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_CONNECT;
Junyu Lai155760b2023-10-05 14:51:00 +0800141import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
142import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
143import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Maciej Żenczykowski22db5902024-05-10 06:44:08 -0700144import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_RELEASE;
145import static com.android.net.module.util.BpfUtils.BPF_CGROUP_SETSOCKOPT;
146import static com.android.net.module.util.BpfUtils.BPF_CGROUP_UDP4_RECVMSG;
147import static com.android.net.module.util.BpfUtils.BPF_CGROUP_UDP4_SENDMSG;
148import static com.android.net.module.util.BpfUtils.BPF_CGROUP_UDP6_RECVMSG;
149import static com.android.net.module.util.BpfUtils.BPF_CGROUP_UDP6_SENDMSG;
Xiao Ma60142372022-07-16 17:30:20 +0900150import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Sarup Dalwani18b72622025-02-08 04:06:44 +0000151import static com.android.net.module.util.NetworkStackConstants.IPV4_LOCAL_PREFIXES;
152import static com.android.net.module.util.NetworkStackConstants.MULTICAST_AND_BROADCAST_PREFIXES;
paulhu3ffffe72021-09-16 10:15:22 +0800153import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
154import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
155import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Junyu Lai71b51532024-02-01 10:39:01 +0800156import static com.android.net.module.util.PermissionUtils.hasAnyPermissionOf;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900157import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Suprabh Shuklac623c942024-10-15 17:19:07 -0700158import static com.android.server.connectivity.ConnectivityFlags.CELLULAR_DATA_INACTIVITY_TIMEOUT;
Motomu Utsumi390be062024-05-13 17:56:18 +0900159import static com.android.server.connectivity.ConnectivityFlags.DELAY_DESTROY_SOCKETS;
Remi NGUYEN VAN42dc6e42024-07-17 10:45:38 +0900160import static com.android.server.connectivity.ConnectivityFlags.INGRESS_TO_VPN_ADDRESS_FILTERING;
Suprabh Shukla392336b2024-12-02 16:17:48 -0800161import static com.android.server.connectivity.ConnectivityFlags.NAMESPACE_TETHERING_BOOT;
Remi NGUYEN VAN48d25272024-07-03 18:50:03 +0900162import static com.android.server.connectivity.ConnectivityFlags.QUEUE_CALLBACKS_FOR_FROZEN_APPS;
Chalard Jean391ec5d2025-03-07 10:54:52 +0900163import static com.android.server.connectivity.ConnectivityFlags.QUEUE_NETWORK_AGENT_EVENTS_IN_SYSTEM_SERVER;
Ying Xu7cabd322024-01-15 18:40:15 -0800164import static com.android.server.connectivity.ConnectivityFlags.REQUEST_RESTRICTED_WIFI;
Suprabh Shuklac623c942024-10-15 17:19:07 -0700165import static com.android.server.connectivity.ConnectivityFlags.WIFI_DATA_INACTIVITY_TIMEOUT;
Motomu Utsumib4772b12023-10-23 17:08:27 +0900166
Chalard Jean5b639762020-03-09 21:25:37 +0900167import android.Manifest;
Junyu Lai71b51532024-02-01 10:39:01 +0800168import android.annotation.CheckResult;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000169import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800170import android.annotation.Nullable;
Maciej Żenczykowskif0da1be2024-06-16 05:02:50 -0700171import android.annotation.RequiresApi;
Michael Groover73f69482023-01-27 11:01:25 -0600172import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800173import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000174import android.app.ActivityManager;
175import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800176import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800177import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700178import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700179import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900180import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800181import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700182import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800183import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800184import android.content.ContentResolver;
185import android.content.Context;
186import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700187import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800188import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900189import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700190import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800191import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900192import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900193import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700194import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800195import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800196import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800197import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900198import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800199import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900200import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800201import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900202import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800203import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700204import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900205import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800206import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800207import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800208import android.net.IDnsResolver;
Patrick Rohr7d6dfd52024-12-05 04:06:53 +0000209import android.net.IIntResultListener;
Luke Huang46289a22018-09-27 19:33:11 +0800210import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800211import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900212import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900213import android.net.INetworkMonitor;
214import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900215import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900216import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700217import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800218import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900219import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900220import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900221import android.net.IpPrefix;
Sarup Dalwani18b72622025-02-08 04:06:44 +0000222import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800223import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900224import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900225import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100226import android.net.MatchAllNetworkSpecifier;
Yang Sun29037f62023-12-04 10:31:58 +0800227import android.net.MulticastRoutingConfig;
Ken Chen6df7a902021-04-09 15:08:42 +0800228import android.net.NativeNetworkConfig;
229import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800230import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700231import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700232import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900233import android.net.NetworkAgentConfig;
Chalard Jean8a976922025-03-18 09:27:33 +0900234import android.net.NetworkAndAgentRegistryParcelable;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700235import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800236import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700237import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900238import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900239import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000240import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900241import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700242import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900243import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700244import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900245import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700246import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800247import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900248import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700249import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000250import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800251import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900252import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800253import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400254import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700255import android.net.QosCallbackException;
256import android.net.QosFilter;
257import android.net.QosSocketFilter;
258import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700259import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800260import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800261import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900262import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400263import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800264import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800265import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400266import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800267import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900268import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900269import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900270import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800271import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900272import android.net.networkstack.ModuleNetworkStackClient;
273import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900274import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800275import android.net.resolv.aidl.DnsHealthEventParcel;
276import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
277import android.net.resolv.aidl.Nat64PrefixEventParcel;
278import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900279import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900280import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800281import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800282import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800283import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700284import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000285import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800286import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700287import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700288import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800289import android.os.Looper;
290import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700291import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700292import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900293import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800294import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700295import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700296import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800297import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700298import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900299import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900300import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700301import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700302import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400303import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800304import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900305import android.stats.connectivity.MeteredState;
306import android.stats.connectivity.RequestType;
307import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900308import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700309import android.system.ErrnoException;
Ying Xu0d06b942024-02-09 21:04:08 -0800310import android.telephony.SubscriptionManager;
Wink Saville32506bc2013-06-29 21:10:57 -0700311import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700312import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800313import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900314import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000315import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600316import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900317import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900318import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700319import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700320import android.util.SparseIntArray;
Tommy Webba0dad0a2023-02-20 14:10:55 -0500321import android.util.SparseLongArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900322import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800323
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900324import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400325import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400326import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700327import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900328import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900329import com.android.metrics.ConnectionDurationForTransports;
330import com.android.metrics.ConnectionDurationPerTransports;
331import com.android.metrics.ConnectivitySampleMetricsHelper;
332import com.android.metrics.ConnectivityStateSample;
333import com.android.metrics.NetworkCountForTransports;
334import com.android.metrics.NetworkCountPerTransports;
335import com.android.metrics.NetworkDescription;
336import com.android.metrics.NetworkList;
337import com.android.metrics.NetworkRequestCount;
338import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800339import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900340import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800341import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000342import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900343import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800344import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900345import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900346import com.android.net.module.util.DeviceConfigUtils;
Junyu Lai2ff42d22023-12-07 16:57:13 +0800347import com.android.net.module.util.HandlerUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100348import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900349import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
350import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900351import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800352import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800353import com.android.net.module.util.PermissionUtils;
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +0900354import com.android.net.module.util.RoutingCoordinatorService;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100355import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000356import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800357import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
358import com.android.networkstack.apishim.ConstantsShim;
359import com.android.networkstack.apishim.common.BroadcastOptionsShim;
360import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900361import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900362import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000363import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900364import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800365import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800366import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900367import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900368import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900369import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500370import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700371import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900372import com.android.server.connectivity.FullScore;
Sarup Dalwani53ecd952025-03-05 15:43:22 +0000373import com.android.server.connectivity.InterfaceTracker;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900374import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900375import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000376import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100377import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700378import com.android.server.connectivity.MockableSystemProperties;
Yang Sun29037f62023-12-04 10:31:58 +0800379import com.android.server.connectivity.MulticastRoutingCoordinatorService;
Chalard Jean43aae652022-09-14 21:33:06 +0900380import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700381import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600382import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900383import com.android.server.connectivity.NetworkNotificationManager;
384import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900385import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900386import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900387import com.android.server.connectivity.NetworkRanker;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000388import com.android.server.connectivity.NetworkRequestStateStatsMetrics;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700389import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900390import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900391import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700392import com.android.server.connectivity.QosCallbackTracker;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000393import com.android.server.connectivity.SatelliteAccessController;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800394import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000395import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800396import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600397
Josh Gao461a1222020-06-16 15:58:11 -0700398import libcore.io.IoUtils;
399
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900400import org.xmlpull.v1.XmlPullParserException;
401
The Android Open Source Project28527d22009-03-03 19:31:44 -0800402import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100403import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900404import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800405import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900406import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700407import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700408import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900409import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900410import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700411import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700412import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700413import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700414import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800415import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900416import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800417import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700418import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700419import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700420import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700421import java.util.Map;
Yang Sun29037f62023-12-04 10:31:58 +0800422import java.util.Map.Entry;
Chalard Jean524f0b12021-10-25 21:11:56 +0900423import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700424import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900425import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600426import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900427import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600428import java.util.TreeSet;
Motomu Utsumi7b906de2024-08-30 19:44:54 +0900429import java.util.concurrent.CopyOnWriteArraySet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900430import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900431import java.util.concurrent.atomic.AtomicInteger;
Chalard Jeanf34735e2025-02-07 16:11:46 +0900432import java.util.concurrent.atomic.AtomicReference;
Ying Xu0d06b942024-02-09 21:04:08 -0800433import java.util.function.BiConsumer;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000434import java.util.function.Consumer;
Chalard Jean2f52a0e2025-03-21 10:14:28 +0900435import java.util.function.Predicate;
Tommy Webba0dad0a2023-02-20 14:10:55 -0500436import java.util.stream.Collectors;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800437
438/**
439 * @hide
440 */
Chalard Jeanf34735e2025-02-07 16:11:46 +0900441public class ConnectivityService extends IConnectivityManager.Stub {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900442 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800443
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900444 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900445 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900446 private static final String NETWORK_ARG = "networks";
447 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800448 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
KH Shi855712a2023-06-21 17:15:35 +0800449 public static final String CLATEGRESS4RAWBPFMAP_ARG = "clatEgress4RawBpfMap";
450 public static final String CLATINGRESS6RAWBPFMAP_ARG = "clatIngress6RawBpfMap";
Erik Klined364a242017-05-12 16:52:48 +0900451
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900452 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900453 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
454 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800455
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900456 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700457
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100458 /**
459 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
460 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800461 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100462 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
463 * (preferably via runtime resource overlays).
464 */
465 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
466 "http://connectivitycheck.gstatic.com/generate_204";
467
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700468 // TODO: create better separation between radio types and network types
469
Robert Greenwalt2034b912009-08-12 16:08:25 -0700470 // how long to wait before switching back to a radio's default network
471 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
472 // system property that can override the above value
473 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
474 "android.telephony.apn-restore";
475
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900476 // How long to wait before putting up a "This network doesn't have an Internet connection,
477 // connect anyway?" dialog after the user selects a network that doesn't validate.
478 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
479
Chalard Jean5fb43c72022-09-08 19:03:14 +0900480 // How long to wait before considering that a network is bad in the absence of any form
481 // of connectivity (valid, partial, captive portal). If none has been detected after this
482 // delay, the stack considers this network bad, which may affect how it's handled in ranking
483 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900484 // Timeout in case the "actively prefer bad wifi" feature is on
485 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
486 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900487 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900488
junyulai0ac374f2020-12-14 18:41:52 +0800489 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900490 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
491 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800492 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700493
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800494 // Delimiter used when creating the broadcast delivery group for sending
495 // CONNECTIVITY_ACTION broadcast.
496 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
497
he_won.hwang881307a2022-03-15 21:23:52 +0900498 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900499 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900500
Daniel Brightf9e945b2020-06-15 16:10:01 -0700501 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900502 @VisibleForTesting
503 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700504
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900505 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700506 @VisibleForTesting
507 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900508
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900509 @VisibleForTesting
510 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800511 @VisibleForTesting
512 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900513 // True if the cell radio of the device is capable of time-sharing.
514 @VisibleForTesting
515 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900516
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800517 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800518 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800519 private final int mReleasePendingIntentDelayMs;
520
Chalard Jean46bfbf02022-02-02 00:56:25 +0900521 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900522
Motomu Utsumif360aa62023-01-30 17:52:20 +0900523 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700524
Chalard Jean9473c982021-07-29 20:03:04 +0900525 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800526 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700527 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800528 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700529
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900530 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700531
Ying Xu7cabd322024-01-15 18:40:15 -0800532 private final boolean mRequestRestrictedWifiEnabled;
Suprabh Shukla724d8972024-03-26 16:59:11 -0700533 private final boolean mBackgroundFirewallChainEnabled;
Ying Xu7cabd322024-01-15 18:40:15 -0800534
Remi NGUYEN VANaa355ac2024-05-29 17:56:17 +0900535 private final boolean mUseDeclaredMethodsForCallbacksEnabled;
Chalard Jean3c040002025-03-18 09:28:41 +0900536 private final boolean mQueueNetworkAgentEventsInSystemServer;
Remi NGUYEN VANaa355ac2024-05-29 17:56:17 +0900537
Remi NGUYEN VAN48d25272024-07-03 18:50:03 +0900538 // Flag to delay callbacks for frozen apps, suppressing duplicate and stale callbacks.
539 private final boolean mQueueCallbacksForFrozenApps;
540
junyulaif2c67e42018-08-07 19:50:45 +0800541 /**
Motomu Utsumid20727f2024-05-23 21:44:40 +0900542 * Uids ConnectivityService tracks blocked status of to send blocked status callbacks.
543 * Key is uid based on mAsUid of registered networkRequestInfo
544 * Value is count of registered networkRequestInfo
545 *
546 * This is necessary because when a firewall chain is enabled or disabled, that affects all UIDs
547 * on the system, not just UIDs on that firewall chain. For example, entering doze mode affects
548 * all UIDs that are not on the dozable chain. ConnectivityService doesn't know which UIDs are
549 * running. But it only needs to send onBlockedStatusChanged to UIDs that have at least one
550 * NetworkCallback registered.
551 *
552 * UIDs are added to this list on the binder thread when processing requestNetwork and similar
553 * IPCs. They are removed from this list on the handler thread, when the callback unregistration
554 * is fully processed. They cannot be unregistered when the unregister IPC is processed because
555 * sometimes requests are unregistered on the handler thread.
556 */
557 @GuardedBy("mBlockedStatusTrackingUids")
558 private final SparseIntArray mBlockedStatusTrackingUids = new SparseIntArray();
559
560 /**
561 * Stale copy of UID blocked reasons. This is used to send onBlockedStatusChanged
562 * callbacks. This is only used on the handler thread, so it does not require a lock.
563 * On U-, the blocked reasons come from NPMS.
564 * On V+, the blocked reasons come from the BPF map contents and only maintains blocked reasons
565 * of uids that register network callbacks.
junyulaif2c67e42018-08-07 19:50:45 +0800566 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900567 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800568
Tommy Webba0dad0a2023-02-20 14:10:55 -0500569 /** Map of UID to its bit-packed allowed transports. */
570 private SparseLongArray mUidAllowedTransports = new SparseLongArray();
571
572 /** Allowed UID ranges provided to Netd, tracked based on the netId to which they belong. */
573 @GuardedBy("mNetworkForNetId")
574 private Map<Integer, NativeUidRangeConfig> mNetIdToAllowlist =
575 new HashMap<Integer, NativeUidRangeConfig>();
576
577 /**
578 * UIDs that we wish to be denied access to networks based on certain policies, grouped by the
579 * netId to which they belong. Used to prevent affected UIDs from getting online through a VPN
580 * or from receiving incoming traffic when their active network is denied to them.
581 */
582 @GuardedBy("mNetworkForNetId")
583 private Map<Integer, List<Integer>> mNetIdToDisallowedUids = new HashMap<>();
584
585 private void setUidsAllowedTransports(@NonNull final int[] uids,
586 @NonNull final long[] allowedTransportsPacked) {
587 mHandler.post(() -> handleSetUidsAllowedTransports(uids, allowedTransportsPacked));
588 }
589
590 private void handleSetUidsAllowedTransports(@NonNull final int[] uids,
591 @NonNull final long[] allowedTransportsPacked) {
592 for (int i = 0; i < uids.length; i++) {
593 final int uid = uids[i];
594 final long transportsPacked = allowedTransportsPacked[i];
595 mUidAllowedTransports.put(uid, transportsPacked);
596 }
597 if (DDBG) Log.d(TAG, "setUidsAllowedTransports: Processing " + uids.length + " UIDs...");
598 for (final var nai : mNetworkAgentInfos) {
599 updateDisallowedUidsForNetwork(nai);
600 if (nai.isVPN()) {
601 // VPNs manage their own allowed UID ranges, so we handle them via denylist above.
602 continue;
603 }
604 for (final int uid : uids) {
605 if (nai.networkCapabilities.appliesToUid(uid)) {
606 updateAllowedUidsForNetwork(nai);
607 break;
608 }
609 }
610 }
611 if (DDBG) Log.d(TAG, "setUidsAllowedTransports: Processed " + uids.length + " UIDs.");
612 }
613
614 // The last UID denylist that we supplied to BPF.
615 // To support access across threads, do not modify after assignment.
616 private Set<Integer> mLastDisallowedUidsDenylist = Set.of();
617
618 /**
619 * Computes which policies apply to the given network to determine which UIDs should be
620 * prevented from accessing that network. Then, for each network with disallowed UIDs, checks
621 * whether the network is currently the active network for the UID, and if so, prevents the
622 * UID from accessing networks entirely via a denylist. Without this, UIDs are able to use VPNs
623 * even if their policy disallows it, because the VPN itself manages its allowed UID ranges.
624 * Additionally, this prevents incoming traffic for UIDs whose active network is disallowed.
625 *
626 * NOTE: UIDs with restricted networking permission are never disallowed.
627 */
628 private void updateDisallowedUidsForNetwork(@NonNull final NetworkAgentInfo nai) {
629 ensureRunningOnConnectivityServiceThread();
630
631 final var netId = nai.network.netId;
632 final var ourTag = "updateDisallowedUidsForNetwork(" + netId + "): ";
633 if (DDBG) Log.d(TAG, ourTag + "begin");
634 final var disallowedUids = getUidsDisallowedByPolicyForNetwork(nai);
635 final Set<Integer> prevDenylist;
636 final Set<Integer> newDenylist = new ArraySet<Integer>();
637 synchronized (mNetworkForNetId) {
638 prevDenylist = mLastDisallowedUidsDenylist;
639 if (mNetworkForNetId.contains(netId)) {
640 // Only store the disallowed UIDs if this network still exists.
641 mNetIdToDisallowedUids.put(netId, disallowedUids);
642 }
643 for (final var entry : mNetIdToDisallowedUids.entrySet()) {
644 final var entryNetId = entry.getKey();
645 final var entryDisallowedUids = entry.getValue();
646 entryDisallowedUids.forEach(uid -> {
647 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
648 // Skip denylist for UIDs with restricted networks permission.
649 return;
650 }
651 // Disallowing UIDs is only applicable if the network is the UID's active
652 // network. For us, a VPN that is still connecting should still be considered,
653 // because it is *about* to become the active network, and we are reacting
654 // early. If we do not include connecting VPNs, we get no result.
655 // Also, if we don't know the active network, denying is fine for now.
656 final var activeNetwork = getActiveNetworkOrConnectingVpnForUidInternal(
657 uid, true /* ignoreBlocked */);
658 if (activeNetwork == null || entryNetId == activeNetwork.netId) {
659 newDenylist.add(uid);
660 }
661 });
662 }
663 mLastDisallowedUidsDenylist = Collections.unmodifiableSet(newDenylist);
664 }
665 // NOTE: Setting UID rules individually is exponentially faster than replacing the whole
666 // firewall chain for some reason (<1ms vs 10+ms, even with few UIDs for the latter
667 // and hundreds for the former).
668 final var toAdd = newDenylist.stream().filter(uid -> !prevDenylist.contains(uid))
669 .collect(Collectors.toSet());
670 if (DDBG) {
671 synchronized (mNetworkForNetId) {
672 Log.d(TAG, ourTag + "Disallowed UIDs per netId: " + mNetIdToDisallowedUids);
673 }
674 Log.d(TAG, ourTag + "Prev denylist: " + prevDenylist);
675 Log.d(TAG, ourTag + "New denylist: " + newDenylist);
676 }
677 final var toRemove = prevDenylist.stream().filter(uid -> !newDenylist.contains(uid))
678 .collect(Collectors.toSet());
679 if (DDBG) Log.d(TAG, ourTag + "toAdd: " + toAdd + "; toRemove: " + toRemove);
680 if (toAdd.isEmpty() && toRemove.isEmpty()) {
681 // Nothing to do.
682 return;
683 }
684 boolean anyFailed = false;
685 for (final int uid : toAdd) {
686 try {
687 mBpfNetMaps.setUidRule(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1, uid,
688 FIREWALL_RULE_DENY);
689 } catch (ServiceSpecificException e) {
690 loge(ourTag + "Failed to add uid " + uid, e);
691 anyFailed = true;
692 break;
693 }
694 }
695 if (!anyFailed) {
696 for (final int uid : toRemove) {
697 try {
698 mBpfNetMaps.setUidRule(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1, uid,
699 FIREWALL_RULE_ALLOW);
700 } catch (ServiceSpecificException e) {
701 loge(ourTag + "Failed to remove uid " + uid, e);
702 anyFailed = true;
703 break;
704 }
705 }
706 }
707 if (anyFailed) {
708 // Should never happen, but just in case.
709 replaceFirewallChain(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1,
710 newDenylist.stream().mapToInt(Integer::intValue).toArray());
711 }
712 // Tell NPMS about the changes, primarily so the firewall icon can reflect them.
713 mPolicyManager.notifyDenylistChanged(toAdd.stream().mapToInt(Integer::intValue).toArray(),
714 toRemove.stream().mapToInt(Integer::intValue).toArray());
715 if (DDBG) Log.d(TAG, ourTag + "end");
716 }
717
718
719 /**
720 * Generates an allowlist configuration for Netd that reflects a network's allowed UIDs and
721 * includes a sub priority to allow the network to act as a default network for the UIDs
722 * if it is considered to be the default network overall. This default network handling is
723 * required, or else UIDs that do not make specific network requests will have no connectivity.
724 */
725 private NativeUidRangeConfig getAllowlistedNativeUidRangeConfigForNetwork(
726 @NonNull final NetworkAgentInfo nai) {
727 final int netId = nai.network.netId;
728 final var uidsAllowedByPolicy = getUidRangeParcelsAllowedByPolicyForNetwork(nai);
729 final boolean isDefault = isDefaultNetwork(nai);
730 final int subPriority = isDefault ? PREFERENCE_ORDER_LOWEST_WITH_DEFAULT
731 : PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT;
732 return new NativeUidRangeConfig(netId, uidsAllowedByPolicy, subPriority);
733 }
734
735 /**
736 * Updates our tracked configurations for Netd based on changes to default networks, and
737 * informs Netd if any changes need to be made to ensure that allowed UIDs do or do not utilize
738 * changed networks as their default network. This default network handling is required, or
739 * else UIDs that do not make specific network requests will have no connectivity or will
740 * have their traffic traverse the wrong network.
741 */
742 private void updateUidDefaultNetworkRules(@Nullable final NetworkAgentInfo newDefaultNetwork) {
743 final Integer defaultNetId = newDefaultNetwork == null ? null
744 : newDefaultNetwork.network.netId;
745 final var configs = new ArrayList<Pair<NativeUidRangeConfig, NativeUidRangeConfig>>();
746 final var networksForUpdateDisallowedUids = new ArrayList<NetworkAgentInfo>();
747 synchronized (mNetworkForNetId) {
748 for (final var config : mNetIdToAllowlist.values()) {
749 final var configIsDefault =
750 config.subPriority == PREFERENCE_ORDER_LOWEST_WITH_DEFAULT;
751 final int subPriority;
752 if (configIsDefault && !Objects.equals(config.netId, defaultNetId)) {
753 // Remove and replace any existing rules with a subPriority for default.
754 subPriority = PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT;
755 } else if (!configIsDefault && Objects.equals(config.netId, defaultNetId)) {
756 // Remove and replace any existing rules with a subPriority for default.
757 subPriority = PREFERENCE_ORDER_LOWEST_WITH_DEFAULT;
758 } else {
759 continue;
760 }
761 final var newConfig =
762 new NativeUidRangeConfig(config.netId, config.uidRanges, subPriority);
763 mNetIdToAllowlist.put(newConfig.netId, newConfig);
764 configs.add(new Pair<>(config, newConfig));
765 final var nai = mNetworkForNetId.get(config.netId);
766 if (nai != null) {
767 networksForUpdateDisallowedUids.add(nai);
768 }
769 }
770 }
771 for (final var pair : configs) {
772 try {
773 mNetd.networkAddUidRangesParcel(pair.second);
774 mNetd.networkRemoveUidRangesParcel(pair.first);
775 } catch (RemoteException | ServiceSpecificException e) {
776 loge("updateUidDefaultNetworkRules: Exception while updating", e);
777 }
778 }
779 for (final var nai : networksForUpdateDisallowedUids) {
780 updateDisallowedUidsForNetwork(nai);
781 }
782 }
783
784 /**
785 * Generates and stores an allowlist configuration based on the policies that apply to the
786 * given network, and sends this configuration to Netd. Uses the same methods for adding UID
787 * range-based IP rules as is used by VPNs or by restricted networks which manually specify
788 * their allowed UIDs, ensuring absent UIDs cannot be routed there. {@see updateAllowedUids}
789 */
790 private void updateAllowedUidsForNetwork(@NonNull final NetworkAgentInfo nai) {
791 if (!nai.networkInfo.isConnected()) {
792 // Network is not connected, so we cannot currently update allowed UIDs.
793 // If we try, Netd responds with: "Machine is not on the network (code 64)"
794 return;
795 }
796 final int netId = nai.network.netId;
797 final var ourTag = "updateAllowedUidsForNetwork(" + netId + "): ";
798 if (DDBG) Log.d(TAG, ourTag + "begin");
799 final var config = getAllowlistedNativeUidRangeConfigForNetwork(nai);
800 final NativeUidRangeConfig lastConfig;
801 synchronized (mNetworkForNetId) {
802 lastConfig = mNetIdToAllowlist.get(netId);
803 mNetIdToAllowlist.put(netId, config);
804 }
805 try {
806 if (config.uidRanges != null && config.uidRanges.length > 0) {
807 mNetd.networkAddUidRangesParcel(config);
808 }
809 if (lastConfig != null && lastConfig.uidRanges != null
810 && lastConfig.uidRanges.length > 0) {
811 mNetd.networkRemoveUidRangesParcel(lastConfig);
812 }
813 } catch (Exception e) {
814 loge(ourTag + "Exception encountered", e);
815 }
816 if (DDBG) Log.d(TAG, ourTag + "end");
817 }
818
819 private static final long TRANSPORT_VPN_FLAG = 1 << TRANSPORT_VPN;
820
821 /**
822 * Returns true if all of the provided transports are allowed, or if transports represent
823 * a VPN and VPNs are allowed. Otherwise, returns false.
824 */
825 private static boolean areTransportsAllowed(final long transports,
826 final long allowedTransports) {
827 // TODO: In the future, we may want to provide a way to restrict VPN access based on
828 // its other transports, e.g. to block apps from using mobile data even if that data
829 // is over a VPN. This is possible by removing or extending the check below.
830 if ((transports & TRANSPORT_VPN_FLAG) != 0) {
831 // For a VPN, all that matters is VPN access, nothing else.
832 return (allowedTransports & TRANSPORT_VPN_FLAG) != 0;
833 }
834 return (allowedTransports & transports) == transports;
835 }
836
837 /**
838 * Returns a list of UIDs that are policy-restricted based on the provided network and its
839 * capabilities. Networks that are restricted by the system choose their own allowed UIDs,
840 * so we do not disallow any UIDs for those networks.
841 */
842 private List<Integer> getUidsDisallowedByPolicyForNetwork(
843 @NonNull final NetworkAgentInfo nai) {
844 final var ourTag = "getUidsDisallowedByPolicyForNetwork(" + nai.network.netId + "): ";
845 final var uids = new ArrayList<Integer>();
846 if (!nai.networkInfo.isConnectedOrConnecting()) {
847 // Network is not connected so nothing needs to be disallowed.
848 if (DDBG) Log.d(TAG, ourTag + "not connected, so empty");
849 return uids;
850 }
851 final NetworkCapabilities nc = nai.networkCapabilities;
852 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
853 // We do not want to meddle with networks that are already considered restricted.
854 // These will have their own allowed UIDs.
855 if (DDBG) Log.d(TAG, ourTag + "restricted, so empty");
856 return uids;
857 }
858 final long packedTransports = BitUtils.packBits(nc.getTransportTypes());
859 if (packedTransports == 0L) {
860 // If we are not supplied with transports to check, nothing is allowed.
861 if (DDBG) Log.d(TAG, ourTag + "transports == 0L, so empty");
862 return uids;
863 }
864 final int size = mUidAllowedTransports.size();
865 int lastUid = 0;
866 for (int i = 0; i < size; i++) {
867 int uid = mUidAllowedTransports.keyAt(i);
868 long allowedTransports = mUidAllowedTransports.valueAt(i);
869 if (!nc.appliesToUid(uid)) continue;
870 if (!areTransportsAllowed(packedTransports, allowedTransports)) {
871 uids.add(uid);
872 }
873 }
874 return uids;
875 }
876
877 /**
878 * Returns an array of UidRangeParcel representing all possible UIDs that are not restricted
879 * by policy, based on the provided network and its capabilities.
880 */
881 private UidRangeParcel[] getUidRangeParcelsAllowedByPolicyForNetwork(
882 @NonNull final NetworkAgentInfo nai) {
883 final var uids = getUidsDisallowedByPolicyForNetwork(nai);
884 final var ranges = new ArrayList<UidRangeParcel>();
885 int lastUid = 0;
886 for (final Integer uid : uids) {
887 if (uid != lastUid) {
888 ranges.add(new UidRangeParcel(lastUid, uid - 1));
889 }
890 lastUid = uid + 1;
891 }
892 ranges.add(new UidRangeParcel(lastUid, Integer.MAX_VALUE));
893 return ranges.toArray(new UidRangeParcel[0]);
894 }
895
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900896 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900897 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000898 private final int mWakeUpMark;
899 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000900 // The Context is created for UserHandle.ALL.
901 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900902 private final Dependencies mDeps;
Jacque Li8d5c6ea2024-10-21 20:02:15 +0000903 private final PermissionMonitor.Dependencies mPermissionMonitorDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900904 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700905 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700906 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800907
Chenbo Feng15416292018-11-08 17:36:21 -0800908 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800909 protected IDnsResolver mDnsResolver;
910 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800911 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700912 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900913 private final NetworkStatsManager mStatsManager;
914 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800915 private final BpfNetMaps mBpfNetMaps;
Sarup Dalwani53ecd952025-03-05 15:43:22 +0000916 private final InterfaceTracker mInterfaceTracker;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700917
Benedict Wong493e04b2018-11-09 14:45:34 -0800918 /**
919 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
920 * instances.
921 */
922 @GuardedBy("mTNSLock")
923 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800924 private final CompanionDeviceManagerProxyService mCdmps;
Yang Sun29037f62023-12-04 10:31:58 +0800925 private final MulticastRoutingCoordinatorService mMulticastRoutingCoordinatorService;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900926 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800927
928 private final Object mTNSLock = new Object();
929
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700930 private String mCurrentTcpBufferSizes;
931
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900932 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000933 new Class[] {
934 ConnectivityService.class,
935 NetworkAgent.class,
936 NetworkAgentInfo.class,
937 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900938
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500939 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400940 // Tear down networks that have no chance (e.g. even if validated) of becoming
941 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500942 // all networks have been rematched against all NetworkRequests.
943 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400944 // Don't reap networks. This should be passed when some networks have not yet been
945 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500946 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900947 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500948
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900949 private enum UnneededFor {
950 LINGER, // Determine whether this network is unneeded and should be lingered.
951 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
952 }
953
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700954 /**
paulhuaa0743d2021-05-26 21:56:03 +0800955 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800956 * should have priority. The order is passed to netd which will use it together
957 * with UID ranges to generate the corresponding IP rule. This serves to
958 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800959 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800960 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000961 * a lower priority, see {@link NativeUidRangeConfig}.
Motomu Utsumi300a83c2024-04-26 18:30:43 +0900962 * Note that only the highest priority preference is applied if the uid is the target of
963 * multiple preferences.
paulhue9913722021-05-26 15:19:20 +0800964 *
paulhu48291862021-07-14 14:53:57 +0800965 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
966 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800967 */
paulhu48291862021-07-14 14:53:57 +0800968 // Used when sending to netd to code for "no order".
969 static final int PREFERENCE_ORDER_NONE = 0;
970 // Order for requests that don't code for a per-app preference. As it is
971 // out of the valid range, the corresponding order should be
972 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800973 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800974 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800975 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800976 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
977 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800978 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800979 static final int PREFERENCE_ORDER_OEM = 10;
980 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800981 // See {@link #setProfileNetworkPreference}.
982 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800983 static final int PREFERENCE_ORDER_PROFILE = 20;
984 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800985 // better scores are connected.
986 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800987 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800988 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000989 // Order of setting satellite network preference fallback when default message application
990 // with role_sms role and android.permission.SATELLITE_COMMUNICATION permission detected
991 @VisibleForTesting
992 static final int PREFERENCE_ORDER_SATELLITE_FALLBACK = 40;
Tommy Webba0dad0a2023-02-20 14:10:55 -0500993 // Lowest subpriority that still adds default network rules.
994 static final int PREFERENCE_ORDER_LOWEST_WITH_DEFAULT = 998;
Chalard Jeane6c95272022-01-25 21:04:21 +0900995 // Preference order that signifies the network shouldn't be set as a default network for
996 // the UIDs, only give them access to it. TODO : replace this with a boolean
997 // in NativeUidRangeConfig
998 @VisibleForTesting
999 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
1000 // Bound for the lowest valid preference order.
1001 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +08001002
1003 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001004 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07001005 * from one net to another. Clear happens when we get a new
1006 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
1007 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001008 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001009 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001010
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001011 /**
1012 * used internally to reload global proxy settings
1013 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001014 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001015
Robert Greenwalt34848c02011-03-25 13:09:25 -07001016 /**
Jason Monka69f1b02013-10-10 14:02:51 -04001017 * PAC manager has received new port.
1018 */
Aaron Huang9fe47be2021-06-08 13:11:45 +08001019 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -04001020
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001021 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +09001022 * used internally when registering NetworkProviders
1023 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001024 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +09001025 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001026
Robert Greenwalte20f7a22014-04-18 15:25:25 -07001027 /**
1028 * used internally when registering NetworkAgents
1029 * obj = Messenger
1030 */
1031 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
1032
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001033 /**
1034 * used to add a network request
1035 * includes a NetworkRequestInfo
1036 */
1037 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
1038
1039 /**
1040 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +09001041 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001042 * cancel it.
1043 * includes a NetworkRequestInfo
1044 */
1045 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
1046
1047 /**
1048 * used to add a network listener - no request
1049 * includes a NetworkRequestInfo
1050 */
1051 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
1052
1053 /**
1054 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -04001055 * arg1 = UID of caller
1056 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001057 */
1058 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
1059
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07001060 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +09001061 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07001062 * obj = Messenger
1063 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +09001064 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07001065
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07001066 /**
1067 * used internally to expire a wakelock when transitioning
1068 * from one net to another. Expire happens when we fail to find
1069 * a new network (typically after 1 minute) -
1070 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
1071 * a replacement network.
1072 */
1073 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
1074
Robert Greenwaltdc2d5612014-08-13 13:43:32 -07001075 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001076 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -04001077 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001078 */
1079 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
1080
1081 /**
1082 * used to remove a pending intent and its associated network request.
1083 * arg1 = UID of caller
1084 * obj = PendingIntent
1085 */
1086 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
1087
Lorenzo Colitti6947c062015-04-03 16:38:52 +09001088 /**
1089 * used to specify whether a network should be used even if unvalidated.
1090 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
1091 * arg2 = whether to remember this choice in the future (1 or 0)
1092 * obj = network
1093 */
1094 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
1095
1096 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001097 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +09001098 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001099 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +09001100
Paul Jensenc8873fc2015-06-17 14:15:39 -04001101 /**
1102 * used to add a network listener with a pending intent
1103 * obj = NetworkRequestInfo
1104 */
1105 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
1106
Hugo Benichid6b510a2017-04-06 17:22:18 +09001107 /**
1108 * used to specify whether a network should not be penalized when it becomes unvalidated.
1109 */
1110 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
1111
1112 /**
Cody Kestingf1120be2020-08-03 18:01:40 -07001113 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +09001114 */
Cody Kestingf1120be2020-08-03 18:01:40 -07001115 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +09001116
Erik Kline31b4a9e2018-01-11 21:07:29 +09001117 // Handle changes in Private DNS settings.
1118 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
1119
dalyk1720e542018-03-05 12:42:22 -05001120 // Handle private DNS validation status updates.
1121 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
1122
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001123 /**
1124 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
1125 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001126 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
1127 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
1128 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001129 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001130 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001131
1132 /**
1133 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
1134 * config was resolved.
1135 * obj = PrivateDnsConfig
1136 * arg2 = netid
1137 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001138 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001139
1140 /**
1141 * Request ConnectivityService display provisioning notification.
1142 * arg1 = Whether to make the notification visible.
1143 * arg2 = NetID.
1144 * obj = Intent to be launched when notification selected by user, null if !arg1.
1145 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001146 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001147
1148 /**
lucaslin2240ef62019-03-12 13:08:03 +08001149 * Used to specify whether a network should be used even if connectivity is partial.
1150 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
1151 * false)
1152 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
1153 * obj = network
1154 */
lucaslin444d43a2020-02-20 16:56:59 +08001155 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +08001156
1157 /**
lucasline117e2e2019-10-22 18:27:33 +08001158 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
1159 * Both of the arguments are bitmasks, and the value of bits come from
1160 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09001161 * arg1 = unused
1162 * arg2 = netId
1163 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +08001164 */
lucaslin444d43a2020-02-20 16:56:59 +08001165 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +08001166
1167 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09001168 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
1169 * arg1 = unused
1170 * arg2 = netId
1171 * obj = captive portal data
1172 */
lucaslin444d43a2020-02-20 16:56:59 +08001173 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09001174
1175 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001176 * Used by setRequireVpnForUids.
1177 * arg1 = whether the specified UID ranges are required to use a VPN.
1178 * obj = Array of UidRange objects.
1179 */
1180 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
1181
1182 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001183 * Used internally when setting the default networks for OemNetworkPreferences.
1184 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -08001185 */
1186 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
1187
1188 /**
lucaslin1193a5d2021-01-21 02:04:15 +08001189 * Used to indicate the system default network becomes active.
1190 */
1191 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
1192
1193 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001194 * Used internally when setting a network preference for a user profile.
1195 * obj = Pair<ProfileNetworkPreference, Listener>
1196 */
1197 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
1198
1199 /**
Motomu Utsumid20727f2024-05-23 21:44:40 +09001200 * Event to update blocked reasons for uids.
1201 * obj = List of Pair(uid, blockedReasons)
Sudheer Shanka9967d462021-03-18 19:09:25 +00001202 */
Motomu Utsumid20727f2024-05-23 21:44:40 +09001203 private static final int EVENT_BLOCKED_REASONS_CHANGED = 51;
Sudheer Shanka9967d462021-03-18 19:09:25 +00001204
1205 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +09001206 * Event to register a new network offer
1207 * obj = NetworkOffer
1208 */
1209 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
1210
1211 /**
1212 * Event to unregister an existing network offer
1213 * obj = INetworkOfferCallback
1214 */
1215 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
1216
1217 /**
paulhu51f77dc2021-06-07 02:34:20 +00001218 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
1219 */
1220 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
1221
1222 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08001223 * Event to set temporary allow bad wifi within a limited time to override
1224 * {@code config_networkAvoidBadWifi}.
1225 */
1226 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
1227
1228 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001229 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
1230 */
1231 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
1232
1233 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +09001234 * The initial evaluation period is over for this network.
1235 *
1236 * If no form of connectivity has been found on this network (valid, partial, captive portal)
1237 * then the stack will now consider it to have been determined bad.
1238 */
1239 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
1240
1241 /**
Hansen Kurli55396972022-10-28 03:31:17 +00001242 * Used internally when the user does not want the network from captive portal app.
1243 * obj = Network
1244 */
1245 private static final int EVENT_USER_DOES_NOT_WANT = 58;
1246
1247 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001248 * Event to set VPN as preferred network for specific apps.
1249 * obj = VpnNetworkPreferenceInfo
1250 */
1251 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
1252
1253 /**
chiachangwange0192a72023-02-06 13:25:01 +00001254 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
1255 */
1256 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
1257
1258 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +00001259 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
1260 */
1261 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
1262
1263 /**
Motomu Utsumiff555a72024-05-23 23:22:40 +09001264 * Event to update firewall socket destroy reasons for uids.
1265 * obj = List of Pair(uid, socketDestroyReasons)
1266 */
1267 private static final int EVENT_UPDATE_FIREWALL_DESTROY_SOCKET_REASONS = 62;
1268
1269 /**
1270 * Event to clear firewall socket destroy reasons for all uids.
1271 * arg1 = socketDestroyReason
1272 */
1273 private static final int EVENT_CLEAR_FIREWALL_DESTROY_SOCKET_REASONS = 63;
1274
1275 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001276 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
1277 * should be shown.
1278 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001279 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001280
1281 /**
1282 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
1283 * should be hidden.
1284 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001285 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001286
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08001287 /**
1288 * The maximum alive time to allow bad wifi configuration for testing.
1289 */
1290 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
1291
Patrick Rohr2857ac42022-01-21 14:58:16 +01001292 /**
chiachangwange0192a72023-02-06 13:25:01 +00001293 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
1294 * testing.
1295 */
1296 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
1297
1298 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001299 * The priority of the tc police rate limiter -- smaller value is higher priority.
1300 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
1301 */
1302 private static final short TC_PRIO_POLICE = 1;
1303
1304 /**
1305 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
1306 */
1307 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -07001308 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +01001309
Hugo Benichi47011212017-03-30 10:46:05 +09001310 private static String eventName(int what) {
1311 return sMagicDecoderRing.get(what, Integer.toString(what));
1312 }
1313
paulhua10d8212020-11-10 15:32:56 +08001314 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +09001315 final DnsResolverServiceManager dsm = context.getSystemService(
1316 DnsResolverServiceManager.class);
1317 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +08001318 }
1319
Cody Kesting73708bf2019-12-18 10:57:50 -08001320 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001321 @VisibleForTesting
1322 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001323 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07001324 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001325 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07001326 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -08001327 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
1328 @VisibleForTesting
1329 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
1330
Erik Kline32120082017-12-13 19:40:49 +09001331 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +09001332 @VisibleForTesting
1333 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001334
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001335 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001336 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001337
Chalard Jean46bfbf02022-02-02 00:56:25 +09001338 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001339 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001340
Chalard Jean5d70ba42018-06-07 16:44:04 +09001341 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
1342 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +08001343 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -04001344
Erik Kline05f2b402015-04-30 12:58:40 +09001345 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001346
Chalard Jean46bfbf02022-02-02 00:56:25 +09001347 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -04001348
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001349 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +09001350 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001351
Valentin Iftime9fa35092019-09-24 13:32:13 +02001352 private Set<String> mWolSupportedInterfaces;
1353
Roshan Pius08c94fb2020-01-16 12:17:17 -08001354 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08001355 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001356 private final AppOpsManager mAppOpsManager;
1357
1358 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -04001359
chiachangwang3d60bac2023-01-17 14:38:08 +00001360 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +09001361 private final QosCallbackTracker mQosCallbackTracker;
1362 private final NetworkNotificationManager mNotifier;
1363 private final LingerMonitor mLingerMonitor;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00001364 private final SatelliteAccessController mSatelliteAccessController;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001365
Patrick Rohr611ce3f2025-01-10 14:20:27 -08001366 private final L2capNetworkProvider mL2capNetworkProvider;
1367
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001368 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +08001369 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001370
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09001371 // Sequence number for NetworkProvider IDs.
1372 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
1373 NetworkProvider.FIRST_PROVIDER_ID);
1374
Erik Klineedf878b2015-07-09 18:24:03 +09001375 // NetworkRequest activity String log entries.
1376 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
1377 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
1378
Hugo Benichid159fdd2016-07-11 11:05:12 +09001379 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +09001380 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +09001381 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
1382
Hugo Benichi47011212017-03-30 10:46:05 +09001383 private static final int MAX_WAKELOCK_LOGS = 20;
1384 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +09001385 private int mTotalWakelockAcquisitions = 0;
1386 private int mTotalWakelockReleases = 0;
1387 private long mTotalWakelockDurationMs = 0;
1388 private long mMaxWakelockDurationMs = 0;
1389 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +09001390
Hugo Benichi208c0102016-07-28 17:53:06 +09001391 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +09001392
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001393 @Nullable private final NetworkRequestStateStatsMetrics mNetworkRequestStateStatsMetrics;
1394
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07001395 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +09001396 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07001397
Erik Kline95ecfee2016-10-02 18:02:14 +09001398 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001399 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +09001400
Lorenzo Colitti389a8142018-01-24 17:35:07 +09001401 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -08001402 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
1403 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -08001404
Patrick Rohr2857ac42022-01-21 14:58:16 +01001405 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
1406 // configured via {@link
1407 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
1408 // Only the handler thread is allowed to access this field.
1409 private long mIngressRateLimit = -1;
1410
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001411 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
1412 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +09001413 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001414 @GuardedBy("mSelfCertifiedCapabilityCache")
1415 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
1416 mSelfCertifiedCapabilityCache = new HashMap<>();
1417
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001418 // Flag to enable the feature of closing frozen app sockets.
1419 private final boolean mDestroyFrozenSockets;
1420
Motomu Utsumi390be062024-05-13 17:56:18 +09001421 // Flag to optimize closing app sockets by waiting for the cellular modem to wake up.
1422 private final boolean mDelayDestroySockets;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001423
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001424 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
1425 private final boolean mAllowSysUiConnectivityReports;
1426
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001427 // Uids that ConnectivityService is pending to close sockets of.
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09001428 // Key is uid and value is reasons of socket destroy
1429 private final SparseIntArray mDestroySocketPendingUids = new SparseIntArray();
1430
1431 private static final int DESTROY_SOCKET_REASON_NONE = 0;
1432 private static final int DESTROY_SOCKET_REASON_FROZEN = 1 << 0;
Motomu Utsumiff555a72024-05-23 23:22:40 +09001433 private static final int DESTROY_SOCKET_REASON_FIREWALL_BACKGROUND = 1 << 1;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001434
Motomu Utsumib4772b12023-10-23 17:08:27 +09001435 // Flag to drop packets to VPN addresses ingressing via non-VPN interfaces.
1436 private final boolean mIngressToVpnAddressFiltering;
1437
Robert Greenwalt802c1102014-06-02 15:32:02 -07001438 /**
1439 * Implements support for the legacy "one network per network type" model.
1440 *
1441 * We used to have a static array of NetworkStateTrackers, one for each
1442 * network type, but that doesn't work any more now that we can have,
1443 * for example, more that one wifi network. This class stores all the
1444 * NetworkAgentInfo objects that support a given type, but the legacy
1445 * API will only see the first one.
1446 *
1447 * It serves two main purposes:
1448 *
1449 * 1. Provide information about "the network for a given type" (since this
1450 * API only supports one).
1451 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
1452 * the first network for a given type changes, or if the default network
1453 * changes.
1454 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001455 @VisibleForTesting
1456 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001457
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09001458 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001459 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001460
Robert Greenwalt802c1102014-06-02 15:32:02 -07001461 /**
1462 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1463 * Each list holds references to all NetworkAgentInfos that are used to
1464 * satisfy requests for that network type.
1465 *
1466 * This array is built out at startup such that an unsupported network
1467 * doesn't get an ArrayList instance, making this a tristate:
1468 * unsupported, supported but not active and active.
1469 *
1470 * The actual lists are populated when we scan the network types that
1471 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001472 *
1473 * Threading model:
1474 * - addSupportedType() is only called in the constructor
1475 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1476 * They are therefore not thread-safe with respect to each other.
1477 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1478 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001479 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001480 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001481 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001482 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001483 @NonNull
1484 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001485
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001486 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1487 // an entry have no timer (equivalent to -1). Lazily loaded.
1488 @NonNull
1489 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1490
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001491 LegacyTypeTracker(@NonNull ConnectivityService service) {
1492 mService = service;
1493 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001494 }
1495
Chiachang Wang3bc52762021-11-25 14:17:57 +08001496 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1497 // addressed.
1498 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001499 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1500 final PackageManager pm = ctx.getPackageManager();
1501 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1502 addSupportedType(TYPE_WIFI);
1503 }
1504 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1505 addSupportedType(TYPE_WIFI_P2P);
1506 }
1507 if (tm.isDataCapable()) {
1508 // Telephony does not have granular support for these types: they are either all
1509 // supported, or none is supported
1510 addSupportedType(TYPE_MOBILE);
1511 addSupportedType(TYPE_MOBILE_MMS);
1512 addSupportedType(TYPE_MOBILE_SUPL);
1513 addSupportedType(TYPE_MOBILE_DUN);
1514 addSupportedType(TYPE_MOBILE_HIPRI);
1515 addSupportedType(TYPE_MOBILE_FOTA);
1516 addSupportedType(TYPE_MOBILE_IMS);
1517 addSupportedType(TYPE_MOBILE_CBS);
1518 addSupportedType(TYPE_MOBILE_IA);
1519 addSupportedType(TYPE_MOBILE_EMERGENCY);
1520 }
1521 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1522 addSupportedType(TYPE_BLUETOOTH);
1523 }
1524 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1525 // TYPE_PROXY is only used on Wear
1526 addSupportedType(TYPE_PROXY);
1527 }
1528 // Ethernet is often not specified in the configs, although many devices can use it via
1529 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001530 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001531 addSupportedType(TYPE_ETHERNET);
1532 }
1533
1534 // Always add TYPE_VPN as a supported type
1535 addSupportedType(TYPE_VPN);
1536 }
1537
1538 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001539 if (mTypeLists[type] != null) {
1540 throw new IllegalStateException(
1541 "legacy list for type " + type + "already initialized");
1542 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001543 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001544 }
1545
Robert Greenwalt802c1102014-06-02 15:32:02 -07001546 public boolean isTypeSupported(int type) {
1547 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1548 }
1549
1550 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001551 synchronized (mTypeLists) {
1552 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1553 return mTypeLists[type].get(0);
1554 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001555 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001556 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001557 }
1558
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001559 public int getRestoreTimerForType(int type) {
1560 synchronized (mTypeLists) {
1561 if (mRestoreTimers == null) {
1562 mRestoreTimers = loadRestoreTimers();
1563 }
1564 return mRestoreTimers.getOrDefault(type, -1);
1565 }
1566 }
1567
1568 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1569 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001570 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001571 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1572 for (final String config : configs) {
1573 final String[] splits = TextUtils.split(config, ",");
1574 if (splits.length != 2) {
1575 logwtf("Invalid restore timer token count: " + config);
1576 continue;
1577 }
1578 try {
1579 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1580 } catch (NumberFormatException e) {
1581 logwtf("Invalid restore timer number format: " + config, e);
1582 }
1583 }
1584 return ret;
1585 }
1586
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001587 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001588 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001589 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001590 log("Sending " + state
1591 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001592 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001593 }
1594 }
1595
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001596 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1597 // network type, to preserve previous behaviour.
1598 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1599 if (vpnNai != mService.getLegacyLockdownNai()) return;
1600
1601 if (vpnNai.declaredUnderlyingNetworks == null
1602 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1603 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1604 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1605 return;
1606 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001607 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001608 vpnNai.declaredUnderlyingNetworks[0]);
1609 if (underlyingNai == null) return;
1610
1611 final int type = underlyingNai.networkInfo.getType();
1612 final DetailedState state = DetailedState.CONNECTED;
1613 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1614 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1615 }
1616
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001617 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001618 public void add(int type, NetworkAgentInfo nai) {
1619 if (!isTypeSupported(type)) {
1620 return; // Invalid network type.
1621 }
1622 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1623
1624 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1625 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001626 return;
1627 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001628 synchronized (mTypeLists) {
1629 list.add(nai);
1630 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001631
Chalard Jean5b409c72021-02-04 13:12:59 +09001632 // Send a broadcast if this is the first network of its type or if it's the default.
1633 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001634
1635 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1636 // to preserve previous behaviour.
1637 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001638 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001639 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1640 mService.sendLegacyNetworkBroadcast(nai, state, type);
1641 }
1642
1643 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1644 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001645 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001646 }
1647
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001648 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001649 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001650 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1651 if (list == null || list.isEmpty()) {
1652 return;
1653 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001654 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001655
Hugo Benichi389633f2016-06-21 09:48:07 +09001656 synchronized (mTypeLists) {
1657 if (!list.remove(nai)) {
1658 return;
1659 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001660 }
1661
Lorenzo Colitti49767722015-05-01 00:30:10 +09001662 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001663 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1664 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001665 }
1666
1667 if (!list.isEmpty() && wasFirstNetwork) {
1668 if (DBG) log("Other network available for type " + type +
1669 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001670 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001671 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001672 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001673 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001674 }
1675 }
1676
1677 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001678 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1679 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001680 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001681 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001682 }
1683 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001684
Chalard Jean46bfbf02022-02-02 00:56:25 +09001685 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001686 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001687 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001688 final DetailedState state = nai.networkInfo.getDetailedState();
1689 for (int type = 0; type < mTypeLists.length; type++) {
1690 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001691 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001692 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001693 if (isFirst || contains && isDefault) {
1694 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001695 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001696 }
1697 }
1698 }
1699
Robert Greenwalt94e22142014-07-30 16:31:24 -07001700 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001701 pw.println("mLegacyTypeTracker:");
1702 pw.increaseIndent();
1703 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001704 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001705 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001706 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001707 pw.println();
1708 pw.println("Current state:");
1709 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001710 synchronized (mTypeLists) {
1711 for (int type = 0; type < mTypeLists.length; type++) {
1712 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1713 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001714 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001715 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001716 }
1717 }
1718 pw.decreaseIndent();
1719 pw.decreaseIndent();
1720 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001721 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001722 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001723 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001724
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001725 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001726 /**
1727 * Helper class which parses out priority arguments and dumps sections according to their
1728 * priority. If priority arguments are omitted, function calls the legacy dump command.
1729 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001730 private class LocalPriorityDump {
1731 private static final String PRIORITY_ARG = "--dump-priority";
1732 private static final String PRIORITY_ARG_HIGH = "HIGH";
1733 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001734 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001735
1736 LocalPriorityDump() {}
1737
1738 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001739 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> {
Junyu Laif8dba342023-10-12 17:01:03 +08001740 doDump(fd, pw, new String[]{DIAG_ARG});
1741 doDump(fd, pw, new String[]{SHORT_ARG});
1742 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1743 pw.println("dumpHigh timeout");
1744 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001745 }
1746
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001747 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001748 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> doDump(fd, pw, args),
Junyu Laif8dba342023-10-12 17:01:03 +08001749 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1750 pw.println("dumpNormal timeout");
1751 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001752 }
1753
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001754 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1755 if (args == null) {
1756 dumpNormal(fd, pw, args);
1757 return;
1758 }
1759
1760 String priority = null;
1761 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1762 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1763 argIndex++;
1764 priority = args[argIndex];
1765 }
1766 }
1767
1768 if (PRIORITY_ARG_HIGH.equals(priority)) {
1769 dumpHigh(fd, pw);
1770 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1771 dumpNormal(fd, pw, args);
1772 } else {
1773 // ConnectivityService publishes binder service using publishBinderService() with
1774 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001775 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1776 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001777 // TODO: Integrate into signal dump.
1778 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001779 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001780 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001781 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001782
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001783 /**
1784 * Dependencies of ConnectivityService, for injection in tests.
1785 */
1786 @VisibleForTesting
1787 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001788 public int getCallingUid() {
1789 return Binder.getCallingUid();
1790 }
1791
Chalard Jeandf29a852023-05-29 17:02:43 +09001792 public boolean isAtLeastS() {
1793 return SdkLevel.isAtLeastS();
1794 }
1795
1796 public boolean isAtLeastT() {
1797 return SdkLevel.isAtLeastT();
1798 }
1799
1800 public boolean isAtLeastU() {
1801 return SdkLevel.isAtLeastU();
1802 }
1803
Chalard Jeaneb663892023-10-07 15:17:07 +09001804 public boolean isAtLeastV() {
1805 return SdkLevel.isAtLeastV();
1806 }
1807
Junyu Lai0b806fd2025-03-19 07:30:11 +08001808 public boolean isAtLeastB() {
1809 return SdkLevel.isAtLeastB();
1810 }
1811
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001812 /**
1813 * Get system properties to use in ConnectivityService.
1814 */
1815 public MockableSystemProperties getSystemProperties() {
1816 return new MockableSystemProperties();
1817 }
1818
1819 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001820 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1821 */
1822 public ConnectivityResources getResources(@NonNull Context ctx) {
1823 return new ConnectivityResources(ctx);
1824 }
1825
1826 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001827 * Create a HandlerThread to use in ConnectivityService.
1828 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001829 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1830 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001831 }
1832
1833 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001834 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001835 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001836 public NetworkStackClientBase getNetworkStack() {
1837 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001838 }
1839
1840 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001841 * @see ProxyTracker
1842 */
1843 public ProxyTracker makeProxyTracker(@NonNull Context context,
1844 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001845 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001846 }
1847
1848 /**
1849 * @see NetIdManager
1850 */
1851 public NetIdManager makeNetIdManager() {
1852 return new NetIdManager();
1853 }
1854
1855 /**
1856 * @see NetworkUtils#queryUserAccess(int, int)
1857 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001858 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1859 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001860 }
1861
1862 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001863 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1864 * requires CAP_NET_ADMIN, which the unit tests do not have.
1865 */
1866 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1867 InetSocketAddress remote) {
1868 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1869 }
1870
1871 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001872 * @see MultinetworkPolicyTracker
1873 */
1874 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1875 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1876 return new MultinetworkPolicyTracker(c, h, r);
1877 }
1878
Aaron Huang330a4c02020-10-27 03:36:19 +08001879 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001880 * @see AutomaticOnOffKeepaliveTracker
1881 */
1882 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1883 @NonNull Context c, @NonNull Handler h) {
1884 return new AutomaticOnOffKeepaliveTracker(c, h);
1885 }
1886
Yang Sun29037f62023-12-04 10:31:58 +08001887 public MulticastRoutingCoordinatorService makeMulticastRoutingCoordinatorService(
1888 @NonNull Handler h) {
1889 try {
1890 return new MulticastRoutingCoordinatorService(h);
1891 } catch (UnsupportedOperationException e) {
1892 // Multicast routing is not supported by the kernel
1893 Log.i(TAG, "Skipping unsupported MulticastRoutingCoordinatorService");
1894 return null;
1895 }
1896 }
1897
chiachangwang7c17c282023-02-02 05:58:59 +00001898 /**
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001899 * @see NetworkRequestStateStatsMetrics
1900 */
1901 public NetworkRequestStateStatsMetrics makeNetworkRequestStateStatsMetrics(
1902 Context context) {
1903 // We currently have network requests metric for Watch devices only
1904 if (context.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
1905 return new NetworkRequestStateStatsMetrics();
1906 } else {
1907 return null;
1908 }
1909 }
1910
1911 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001912 * @see BatteryStatsManager
1913 */
1914 public void reportNetworkInterfaceForTransports(Context context, String iface,
1915 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001916 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001917 context.getSystemService(BatteryStatsManager.class);
1918 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1919 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001920
1921 public boolean getCellular464XlatEnabled() {
1922 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1923 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001924
1925 /**
1926 * @see PendingIntent#intentFilterEquals
1927 */
1928 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1929 return a.intentFilterEquals(b);
1930 }
1931
1932 /**
1933 * @see LocationPermissionChecker
1934 */
1935 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1936 return new LocationPermissionChecker(context);
1937 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001938
1939 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001940 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001941 *
1942 * This method returns null in versions before T, where carrier privilege
1943 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001944 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001945 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001946 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
Ying Xu7cabd322024-01-15 18:40:15 -08001947 @NonNull final Context context,
1948 @NonNull final TelephonyManager tm,
1949 boolean requestRestrictedWifiEnabled,
Motomu Utsumi4fcaa4e2024-02-28 17:15:41 +09001950 @NonNull BiConsumer<Integer, Integer> listener,
1951 @NonNull final Handler connectivityServiceHandler) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001952 if (isAtLeastT()) {
Motomu Utsumi4fcaa4e2024-02-28 17:15:41 +09001953 return new CarrierPrivilegeAuthenticator(context, tm, requestRestrictedWifiEnabled,
1954 listener, connectivityServiceHandler);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001955 } else {
1956 return null;
1957 }
1958 }
1959
1960 /**
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00001961 * @see SatelliteAccessController
1962 */
1963 @Nullable
1964 public SatelliteAccessController makeSatelliteAccessController(
1965 @NonNull final Context context,
1966 Consumer<Set<Integer>> updateSatelliteNetworkFallbackUidCallback,
1967 @NonNull final Handler connectivityServiceInternalHandler) {
1968 return new SatelliteAccessController(context, updateSatelliteNetworkFallbackUidCallback,
1969 connectivityServiceInternalHandler);
1970 }
1971
Patrick Rohr611ce3f2025-01-10 14:20:27 -08001972 /** Creates an L2capNetworkProvider */
1973 public L2capNetworkProvider makeL2capNetworkProvider(Context context) {
1974 return new L2capNetworkProvider(context);
1975 }
1976
Suprabh Shuklac623c942024-10-15 17:19:07 -07001977 /** Returns the data inactivity timeout to be used for cellular networks */
1978 public int getDefaultCellularDataInactivityTimeout() {
Suprabh Shukla392336b2024-12-02 16:17:48 -08001979 return DeviceConfigUtils.getDeviceConfigPropertyInt(NAMESPACE_TETHERING_BOOT,
Suprabh Shuklac623c942024-10-15 17:19:07 -07001980 CELLULAR_DATA_INACTIVITY_TIMEOUT, 10);
1981 }
1982
1983 /** Returns the data inactivity timeout to be used for WiFi networks */
1984 public int getDefaultWifiDataInactivityTimeout() {
Suprabh Shukla392336b2024-12-02 16:17:48 -08001985 return DeviceConfigUtils.getDeviceConfigPropertyInt(NAMESPACE_TETHERING_BOOT,
Suprabh Shuklac623c942024-10-15 17:19:07 -07001986 WIFI_DATA_INACTIVITY_TIMEOUT, 15);
1987 }
1988
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00001989 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001990 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001991 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001992 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001993 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001994 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001995
1996 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001997 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1998 */
1999 public boolean isFeatureNotChickenedOut(Context context, String name) {
2000 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
2001 }
2002
2003 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08002004 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002005 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08002006 * @return BpfNetMaps implementation.
2007 */
Sarup Dalwani53ecd952025-03-05 15:43:22 +00002008 public BpfNetMaps getBpfNetMaps(Context context, INetd netd,
2009 InterfaceTracker interfaceTracker) {
2010 return new BpfNetMaps(context, netd, interfaceTracker);
2011 }
2012
2013 /**
2014 * Get the InterfaceTracker implementation to use in ConnectivityService.
2015 * @return InterfaceTracker implementation.
2016 */
2017 public InterfaceTracker getInterfaceTracker(Context context) {
2018 return new InterfaceTracker(context);
Wayne Ma2fde98c2022-01-17 18:04:05 +08002019 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01002020
2021 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08002022 * @see ClatCoordinator
2023 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07002024 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08002025 public ClatCoordinator getClatCoordinator(INetd netd) {
2026 return new ClatCoordinator(
2027 new ClatCoordinator.Dependencies() {
2028 @NonNull
2029 public INetd getNetd() {
2030 return netd;
2031 }
2032 });
2033 }
2034
2035 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01002036 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
2037 */
2038 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
2039 final InterfaceParams params = InterfaceParams.getByName(iface);
2040 if (params == null) {
2041 // the interface might have disappeared.
2042 logw("Failed to get interface params for interface " + iface);
2043 return;
2044 }
2045 try {
2046 // converting rateInBytesPerSecond from long to int is safe here because the
2047 // setting's range is limited to INT_MAX.
2048 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01002049 Log.i(TAG,
2050 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01002051 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
2052 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
2053 } catch (IOException e) {
2054 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
2055 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
2056 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
2057 + ") failure: ", e);
2058 }
2059 }
2060
2061 /**
2062 * Wraps {@link TcUtils#tcFilterDelDev}
2063 */
2064 public void disableIngressRateLimit(String iface) {
2065 final InterfaceParams params = InterfaceParams.getByName(iface);
2066 if (params == null) {
2067 // the interface might have disappeared.
2068 logw("Failed to get interface params for interface " + iface);
2069 return;
2070 }
2071 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01002072 Log.i(TAG,
2073 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002074 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
2075 } catch (IOException e) {
2076 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
2077 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
2078 }
2079 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08002080
2081 /**
Junyu Lai155760b2023-10-05 14:51:00 +08002082 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
2083 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00002084 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08002085 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00002086 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08002087 }
2088
2089 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08002090 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
2091 */
2092 // TODO: when available in all active branches:
2093 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
2094 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
2095 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
2096 return BroadcastOptionsShimImpl.newInstance(options);
2097 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09002098
2099 /**
2100 * Wrapper method for
2101 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
2102 *
2103 * @param changeId The ID of the compatibility change in question.
2104 * @param packageName The package name of the app in question.
2105 * @param user The user that the operation is done for.
2106 * @return {@code true} if the change is enabled for the specified package.
2107 */
2108 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
2109 @NonNull final UserHandle user) {
2110 return CompatChanges.isChangeEnabled(changeId, packageName, user);
2111 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09002112
2113 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09002114 * As above but with a UID.
2115 * @see CompatChanges#isChangeEnabled(long, int)
2116 */
2117 public boolean isChangeEnabled(final long changeId, final int uid) {
2118 return CompatChanges.isChangeEnabled(changeId, uid);
2119 }
2120
2121 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09002122 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
2123 *
2124 * @param ranges target uid ranges
2125 * @param exemptUids uids to skip close socket
2126 */
2127 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
2128 @NonNull final Set<Integer> exemptUids)
2129 throws SocketException, InterruptedIOException, ErrnoException {
2130 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
2131 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09002132
2133 /**
2134 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
2135 *
2136 * @param ownerUids target uids to close sockets
2137 */
2138 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
2139 throws SocketException, InterruptedIOException, ErrnoException {
2140 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
2141 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09002142
2143 /**
2144 * Schedule the evaluation timeout.
2145 *
2146 * When a network connects, it's "not evaluated" yet. Detection events cause the network
2147 * to be "evaluated" (typically, validation or detection of a captive portal). If none
2148 * of these events happen, this time will run out, after which the network is considered
2149 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
2150 * on this network and considers it won't provide connectivity. In particular, that means
2151 * it's when the system prefers it to cell if it's wifi and configuration says it should
2152 * prefer bad wifi to cell.
2153 */
2154 public void scheduleEvaluationTimeout(@NonNull Handler handler,
2155 @NonNull final Network network, final long delayMs) {
2156 handler.sendMessageDelayed(
2157 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
2158 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09002159 }
2160
junyulaie7c7d2a2021-01-26 15:29:15 +08002161 public ConnectivityService(Context context) {
2162 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09002163 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
Jacque Li8d5c6ea2024-10-21 20:02:15 +00002164 new Dependencies(), new PermissionMonitor.Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09002165 }
2166
2167 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08002168 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
Jacque Li8d5c6ea2024-10-21 20:02:15 +00002169 IpConnectivityLog logger, INetd netd, Dependencies deps,
2170 PermissionMonitor.Dependencies mPermDeps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002171 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08002172
Daulet Zhanguzinee674252020-03-26 12:30:39 +00002173 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09002174 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09002175 mSystemProperties = mDeps.getSystemProperties();
2176 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00002177 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09002178 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08002179 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
2180 // Pass limit - 1 to maintain backward compatibility.
2181 // TODO: Remove the workaround.
2182 mNetworkRequestCounter =
2183 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
2184 mSystemNetworkRequestCounter =
2185 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09002186
Hugo Benichi208c0102016-07-28 17:53:06 +09002187 mMetricsLog = logger;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00002188 mNetworkRequestStateStatsMetrics = mDeps.makeNetworkRequestStateStatsMetrics(mContext);
James Mattis45d81842021-01-10 14:24:24 -08002189 final NetworkRequest defaultInternetRequest = createDefaultRequest();
2190 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09002191 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09002192 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09002193 null /* attributionTags */, DECLARED_METHODS_NONE);
Chalard Jean5b409c72021-02-04 13:12:59 +09002194 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
2195 mDefaultNetworkRequests.add(mDefaultRequest);
2196 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09002197
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09002198 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002199 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07002200
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002201 // The default WiFi request is a background request so that apps using WiFi are
2202 // migrated to a better network (typically ethernet) when one comes up, instead
2203 // of staying on WiFi forever.
2204 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
2205 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
2206
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002207 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
2208 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
2209 NetworkRequest.Type.BACKGROUND_REQUEST);
2210
Chalard Jean0702f982021-09-16 21:50:07 +09002211 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
2212 // TODO: Consider making the timer customizable.
2213 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
2214 mCellularRadioTimesharingCapable =
2215 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
2216
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00002217 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
2218 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
2219
2220 if (SdkLevel.isAtLeastU()) {
2221 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
2222 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
2223 final int defaultUMarkMask = 0x80000000; // u32
2224
2225 if ((mark == 0) || (mask == 0)) {
2226 // simply treat unset/disabled as the default U value
2227 mark = defaultUMarkMask;
2228 mask = defaultUMarkMask;
2229 }
2230 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
2231 // invalid device overlay settings
2232 throw new IllegalArgumentException(
2233 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
2234 }
2235 }
2236
2237 mWakeUpMark = mark;
2238 mWakeUpMask = mask;
2239
Paul Hu51f816b2022-08-11 14:43:47 +00002240 mNetd = netd;
Sarup Dalwani53ecd952025-03-05 15:43:22 +00002241 mInterfaceTracker = mDeps.getInterfaceTracker(mContext);
2242 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd, mInterfaceTracker);
Chalard Jean96ff9542023-11-02 14:24:47 +09002243 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Jacque Li8d5c6ea2024-10-21 20:02:15 +00002244 mPermissionMonitorDeps = mPermDeps;
Paul Hu51f816b2022-08-11 14:43:47 +00002245 mPermissionMonitor =
Jacque Li8d5c6ea2024-10-21 20:02:15 +00002246 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mPermissionMonitorDeps,
2247 mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09002248 mHandlerThread.start();
2249 mHandler = new InternalHandler(mHandlerThread.getLooper());
2250 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08002251 mConnectivityDiagnosticsHandler =
2252 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07002253
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08002254 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08002255 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08002256
junyulaie7c7d2a2021-01-26 15:29:15 +08002257 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08002258 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00002259 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09002260 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09002261
Wink Saville32506bc2013-06-29 21:10:57 -07002262 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002263 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09002264 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Ying Xu7cabd322024-01-15 18:40:15 -08002265 mRequestRestrictedWifiEnabled = mDeps.isAtLeastU()
2266 && mDeps.isFeatureEnabled(context, REQUEST_RESTRICTED_WIFI);
Suprabh Shukla724d8972024-03-26 16:59:11 -07002267 mBackgroundFirewallChainEnabled = mDeps.isAtLeastV() && mDeps.isFeatureNotChickenedOut(
2268 context, ConnectivityFlags.BACKGROUND_FIREWALL_CHAIN);
Lorenzo Colitti21695222025-02-26 03:03:32 +09002269 mUseDeclaredMethodsForCallbacksEnabled =
2270 mDeps.isFeatureNotChickenedOut(context,
2271 ConnectivityFlags.USE_DECLARED_METHODS_FOR_CALLBACKS);
Chalard Jean3d0e3122025-03-21 12:58:21 +09002272 mQueueNetworkAgentEventsInSystemServer = mDeps.isAtLeastB()
2273 && mDeps.isFeatureNotChickenedOut(context,
Chalard Jean3c040002025-03-18 09:28:41 +09002274 ConnectivityFlags.QUEUE_NETWORK_AGENT_EVENTS_IN_SYSTEM_SERVER);
Remi NGUYEN VAN48d25272024-07-03 18:50:03 +09002275 // registerUidFrozenStateChangedCallback is only available on U+
2276 mQueueCallbacksForFrozenApps = mDeps.isAtLeastU()
Lorenzo Colitti21695222025-02-26 03:03:32 +09002277 && mDeps.isFeatureNotChickenedOut(context, QUEUE_CALLBACKS_FOR_FROZEN_APPS);
Ying Xu7cabd322024-01-15 18:40:15 -08002278 mCarrierPrivilegeAuthenticator = mDeps.makeCarrierPrivilegeAuthenticator(
2279 mContext, mTelephonyManager, mRequestRestrictedWifiEnabled,
Motomu Utsumi4fcaa4e2024-02-28 17:15:41 +09002280 this::handleUidCarrierPrivilegesLost, mHandler);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002281
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00002282 if (mDeps.isAtLeastU()
2283 && mDeps
2284 .isFeatureNotChickenedOut(mContext, ALLOW_SATALLITE_NETWORK_FALLBACK)) {
2285 mSatelliteAccessController = mDeps.makeSatelliteAccessController(
2286 mContext, this::updateSatelliteNetworkPreferenceUids, mHandler);
2287 } else {
2288 mSatelliteAccessController = null;
2289 }
2290
Tommy Webba0dad0a2023-02-20 14:10:55 -05002291 // Enable the OEM denylist chain. {@see mNetIdToDisallowedUids}
2292 try {
2293 mBpfNetMaps.setChildChain(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1, true);
2294 } catch (ServiceSpecificException e) {
2295 logwtf("Could not enable fw_oem_deny_1 chain", e);
2296 }
2297
Sudheer Shanka9967d462021-03-18 19:09:25 +00002298 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08002299 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
2300 // reading existing policy from disk.
Motomu Utsumid20727f2024-05-23 21:44:40 +09002301 // If shouldTrackUidsForBlockedStatusCallbacks() is true (On V+), ConnectivityService
2302 // updates blocked reasons when firewall chain and data saver status is updated based on
2303 // bpf map contents instead of receiving callbacks from NPMS
2304 if (!shouldTrackUidsForBlockedStatusCallbacks()) {
2305 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
2306 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002307
2308 final PowerManager powerManager = (PowerManager) context.getSystemService(
2309 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002310 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08002311 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002312
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002313 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
2314 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002315 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002316 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002317 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002318 mProtectedNetworks.add(p);
2319 } else {
2320 if (DBG) loge("Ignoring protectedNetwork " + p);
2321 }
2322 }
2323
soma, kawata29444ae2019-05-23 09:30:40 +09002324 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
2325
James Mattis02220e22021-03-13 19:27:21 -08002326 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09002327 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08002328 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08002329 final IntentFilter userIntentFilter = new IntentFilter();
2330 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
2331 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
2332 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
2333 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08002334
James Mattis02220e22021-03-13 19:27:21 -08002335 // Listen to package add/removes for netd
2336 final IntentFilter packageIntentFilter = new IntentFilter();
2337 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
2338 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2339 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
2340 packageIntentFilter.addDataScheme("package");
2341 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09002342 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08002343
Junyu Lai38c75032023-12-04 07:52:19 +00002344 // This is needed for pre-V devices to propagate the data saver status
2345 // to the BPF map. This isn't supported before Android T because BPF maps are
2346 // unsupported, and it's also unnecessary on Android V and later versions,
2347 // as the platform code handles data saver bit updates. Additionally, checking
2348 // the initial data saver status here is superfluous because the intent won't
2349 // be sent until the system is ready.
2350 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
2351 final IntentFilter dataSaverIntentFilter =
2352 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
2353 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
2354 null /* broadcastPermission */, mHandler);
2355 }
2356
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09002357 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
2358 // But reading the trunk stable flags from mainline modules is not supported yet.
2359 // So enabling this feature on V+ release.
2360 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
Suprabh Shuklac623c942024-10-15 17:19:07 -07002361 final int defaultCellularDataInactivityTimeout =
2362 mDeps.getDefaultCellularDataInactivityTimeout();
2363 final int defaultWifiDataInactivityTimeout =
2364 mDeps.getDefaultWifiDataInactivityTimeout();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09002365 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
Suprabh Shuklac623c942024-10-15 17:19:07 -07002366 mTrackMultiNetworkActivities, defaultCellularDataInactivityTimeout,
2367 defaultWifiDataInactivityTimeout);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07002368
Chalard Jean46bfbf02022-02-02 00:56:25 +09002369 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08002370 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002371 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08002372 } catch (RemoteException | ServiceSpecificException e) {
2373 loge("Error registering event listener :" + e);
2374 }
2375
Erik Kline05f2b402015-04-30 12:58:40 +09002376 mSettingsObserver = new SettingsObserver(mContext, mHandler);
2377 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002378
chiachangwang7c17c282023-02-02 05:58:59 +00002379 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08002380 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07002381 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09002382
2383 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08002384 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09002385 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
2386 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08002387 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09002388 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
2389 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09002390
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09002391 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09002392 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09002393 mNetworkRanker =
2394 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
2395
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09002396 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09002397
Chiachang Wangc1215d32020-10-20 15:38:58 +08002398 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002399 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08002400
Chalard Jean28018572020-12-21 18:36:52 +09002401 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
2402 // request that doesn't allow fallback to the default network. It should never be visible
2403 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
2404 // arguments like the handler or the DnsResolver.
2405 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08002406 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08002407 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08002408 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09002409 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09002410 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09002411 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
2412 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07002413
2414 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09002415 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
2416 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
2417 // Even if it could, running on S would at least require mocking out the BPF map,
2418 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
2419 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09002420 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09002421 mDscpPolicyTracker = new DscpPolicyTracker();
2422 }
Tyler Wear72388212021-09-09 14:49:02 -07002423 } catch (ErrnoException e) {
2424 loge("Unable to create DscpPolicyTracker");
2425 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01002426
2427 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
2428 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08002429
Chalard Jeandf29a852023-05-29 17:02:43 +09002430 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08002431 mCdmps = new CompanionDeviceManagerProxyService(context);
2432 } else {
2433 mCdmps = null;
2434 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00002435
Handa Wange5e06f92024-08-14 05:55:21 +00002436 mRoutingCoordinatorService =
2437 new RoutingCoordinatorService(netd, this::getAllNetworks, mContext);
Yang Sun29037f62023-12-04 10:31:58 +08002438 mMulticastRoutingCoordinatorService =
2439 mDeps.makeMulticastRoutingCoordinatorService(mHandler);
Chalard Jean2fb66f12023-08-25 12:50:37 +09002440
Motomu Utsumi701efff2024-02-13 12:46:59 +09002441 mDestroyFrozenSockets = mDeps.isAtLeastV() || (mDeps.isAtLeastU()
2442 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION));
Motomu Utsumi390be062024-05-13 17:56:18 +09002443 mDelayDestroySockets = mDeps.isFeatureNotChickenedOut(context, DELAY_DESTROY_SOCKETS);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09002444 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
2445 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Remi NGUYEN VAN48d25272024-07-03 18:50:03 +09002446 if (mDestroyFrozenSockets || mQueueCallbacksForFrozenApps) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00002447 final UidFrozenStateChangedCallback frozenStateChangedCallback =
2448 new UidFrozenStateChangedCallback() {
2449 @Override
2450 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
2451 if (uids.length != frozenStates.length) {
2452 Log.wtf(TAG, "uids has length " + uids.length
2453 + " but frozenStates has length " + frozenStates.length);
2454 return;
2455 }
2456
2457 final UidFrozenStateChangedArgs args =
2458 new UidFrozenStateChangedArgs(uids, frozenStates);
2459
2460 mHandler.sendMessage(
2461 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
2462 }
2463 };
2464
2465 final ActivityManager activityManager =
2466 mContext.getSystemService(ActivityManager.class);
2467 activityManager.registerUidFrozenStateChangedCallback(
2468 (Runnable r) -> r.run(), frozenStateChangedCallback);
2469 }
Motomu Utsumib4772b12023-10-23 17:08:27 +09002470 mIngressToVpnAddressFiltering = mDeps.isAtLeastT()
2471 && mDeps.isFeatureNotChickenedOut(mContext, INGRESS_TO_VPN_ADDRESS_FILTERING);
Patrick Rohr611ce3f2025-01-10 14:20:27 -08002472
2473 mL2capNetworkProvider = mDeps.makeL2capNetworkProvider(mContext);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002474 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002475
Xiao Ma0a171c02022-01-23 16:14:51 +00002476 /**
2477 * Check whether or not the device supports Ethernet transport.
2478 */
2479 public static boolean deviceSupportsEthernet(final Context context) {
2480 final PackageManager pm = context.getPackageManager();
2481 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
2482 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
2483 }
2484
Chalard Jean46adcf32018-04-18 20:18:38 +09002485 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002486 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
2487 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09002488 }
2489
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002490 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
2491 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09002492 final NetworkCapabilities netCap = new NetworkCapabilities();
2493 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002494 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09002495 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002496 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09002497 return netCap;
2498 }
2499
James Mattis45d81842021-01-10 14:24:24 -08002500 private NetworkRequest createDefaultRequest() {
2501 return createDefaultInternetRequestForTransport(
2502 TYPE_NONE, NetworkRequest.Type.REQUEST);
2503 }
2504
lucaslin3ba7cc22022-12-19 02:35:33 +00002505 private NetworkRequest createVpnRequest() {
2506 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
2507 .withoutDefaultCapabilities()
2508 .addTransportType(TRANSPORT_VPN)
2509 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
2510 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
2511 .build();
2512 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2513 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
2514 }
2515
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09002516 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002517 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09002518 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09002519 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002520 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08002521 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08002522 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09002523 netCap.addTransportType(transportType);
2524 }
James Mattis45d81842021-01-10 14:24:24 -08002525 return createNetworkRequest(type, netCap);
2526 }
2527
2528 private NetworkRequest createNetworkRequest(
2529 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002530 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09002531 }
2532
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002533 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
2534 NetworkRequest.Type type) {
2535 final NetworkCapabilities netCap = new NetworkCapabilities();
2536 netCap.clearAll();
2537 netCap.addCapability(capability);
2538 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2539 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
2540 }
2541
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002542 // Used only for testing.
2543 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07002544 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002545 // changing ContentResolver to make registerContentObserver non-final).
2546 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
2547 // by subclassing SettingsObserver.
2548 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002549 void updateAlwaysOnNetworks() {
2550 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002551 }
2552
Erik Kline9a62f012018-03-21 07:18:33 -07002553 // See FakeSettingsProvider comment above.
2554 @VisibleForTesting
2555 void updatePrivateDnsSettings() {
2556 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
2557 }
2558
paulhu51f77dc2021-06-07 02:34:20 +00002559 @VisibleForTesting
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +09002560 public void updateMobileDataPreferredUids() {
paulhu51f77dc2021-06-07 02:34:20 +00002561 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
2562 }
2563
Patrick Rohr2857ac42022-01-21 14:58:16 +01002564 @VisibleForTesting
2565 void updateIngressRateLimit() {
2566 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
2567 }
2568
Aaron Huang40b52442021-06-08 04:34:24 +08002569 @VisibleForTesting
2570 void simulateUpdateProxyInfo(@Nullable final Network network,
2571 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08002572 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08002573 new Pair<>(network, proxyInfo)).sendToTarget();
2574 }
2575
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00002576 /**
2577 * Called when satellite network fallback uids at {@link SatelliteAccessController}
2578 * cache was updated based on {@link
2579 * android.app.role.OnRoleHoldersChangedListener#onRoleHoldersChanged(String, UserHandle)},
2580 * to create multilayer request with preference order
2581 * {@link #PREFERENCE_ORDER_SATELLITE_FALLBACK} there on.
2582 *
2583 */
2584 private void updateSatelliteNetworkPreferenceUids(Set<Integer> satelliteNetworkFallbackUids) {
2585 handleSetSatelliteNetworkPreference(satelliteNetworkFallbackUids);
2586 }
2587
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002588 private void handleAlwaysOnNetworkRequest(
2589 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002590 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002591 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002592 handleAlwaysOnNetworkRequest(networkRequest, enable);
2593 }
2594
2595 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002596 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002597 if (enable == isEnabled) {
2598 return; // Nothing to do.
2599 }
2600
2601 if (enable) {
2602 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002603 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002604 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09002605 null /* attributionTags */, DECLARED_METHODS_NONE));
Erik Kline05f2b402015-04-30 12:58:40 +09002606 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002607 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2608 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002609 }
2610 }
2611
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002612 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002613 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2614 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2615 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2616 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002617 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2618 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002619 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002620 }
2621
paulhu51f77dc2021-06-07 02:34:20 +00002622 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002623 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002624 private void registerSettingsCallbacks() {
2625 // Watch for global HTTP proxy changes.
2626 mSettingsObserver.observe(
2627 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2628 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2629
Chalard Jean46bfbf02022-02-02 00:56:25 +09002630 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002631 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002632 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002633 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2634
Chalard Jean46bfbf02022-02-02 00:56:25 +09002635 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002636 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002637 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002638 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002639
2640 // Watch for mobile data preferred uids changes.
2641 mSettingsObserver.observe(
2642 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2643 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002644
2645 // Watch for ingress rate limit changes.
2646 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002647 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002648 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2649 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002650 }
2651
Erik Kline31b4a9e2018-01-11 21:07:29 +09002652 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002653 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2654 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002655 }
2656 }
2657
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002658 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002659 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2660 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002661 return mNextNetworkRequestId++;
2662 }
2663
junyulai74f9a8b2018-06-13 15:00:37 +08002664 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002665 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002666 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002667 if (network == null) {
2668 return null;
2669 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002670 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002671 }
2672
2673 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002674 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002675 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002676 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002677 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002678
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002679 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002680 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002681 private NetworkAgentInfo getVpnForUid(int uid) {
2682 synchronized (mNetworkForNetId) {
2683 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2684 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002685 if (nai.isVPN() && nai.everConnected()
2686 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002687 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002688 }
2689 }
2690 }
2691 return null;
2692 }
2693
Chalard Jean46bfbf02022-02-02 00:56:25 +09002694 @Nullable
Tommy Webba0dad0a2023-02-20 14:10:55 -05002695 private NetworkAgentInfo getConnectedOrConnectingVpnForUid(int uid) {
2696 synchronized (mNetworkForNetId) {
2697 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2698 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
2699 if (nai.isVPN()
2700 && (nai.everConnected() || nai.networkInfo.isConnectedOrConnecting())
2701 && nai.networkCapabilities.appliesToUid(uid)) {
2702 return nai;
2703 }
2704 }
2705 }
2706 return null;
2707 }
2708
2709 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002710 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002711 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002712 final NetworkAgentInfo nai = getVpnForUid(uid);
2713 if (nai != null) return nai.declaredUnderlyingNetworks;
2714 return null;
2715 }
2716
Lorenzo Colittia7574052021-01-19 01:33:05 +09002717 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002718 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002719
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002720 final Network[] networks = getVpnUnderlyingNetworks(uid);
2721 if (networks != null) {
2722 // getUnderlyingNetworks() returns:
2723 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2724 // empty array => the VPN explicitly said "no default network".
2725 // non-empty array => the VPN specified one or more default networks; we use the
2726 // first one.
2727 if (networks.length > 0) {
2728 nai = getNetworkAgentInfoForNetwork(networks[0]);
2729 } else {
2730 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002731 }
2732 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002733 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002734 }
2735
Motomu Utsumib15be222024-05-15 18:50:08 +09002736 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
2737 private boolean hasInternetPermission(final int uid) {
2738 return (mBpfNetMaps.getNetPermForUid(uid) & PERMISSION_INTERNET) != 0;
2739 }
2740
Paul Jensen83f5d572014-08-29 09:54:01 -04002741 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002742 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002743 */
paulhu7aeba372020-12-30 00:42:19 +08002744 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2745 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002746 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002747 if (ignoreBlocked) {
2748 return false;
2749 }
Tommy Webba0dad0a2023-02-20 14:10:55 -05002750 if (isUidCurrentlyDisallowedByPolicy(uid)) return true;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002751 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002752 final long ident = Binder.clearCallingIdentity();
2753 try {
2754 final boolean metered = nc == null ? true : nc.isMetered();
Maciej Żenczykowskia08692f2024-04-11 19:49:28 +00002755 if (mDeps.isAtLeastV()) {
Motomu Utsumib15be222024-05-15 18:50:08 +09002756 final boolean hasInternetPermission = hasInternetPermission(uid);
2757 final boolean blockedByUidRules = mBpfNetMaps.isUidNetworkingBlocked(uid, metered);
2758 if (mDeps.isChangeEnabled(NETWORK_BLOCKED_WITHOUT_INTERNET_PERMISSION, uid)) {
2759 return blockedByUidRules || !hasInternetPermission;
2760 } else {
2761 return hasInternetPermission && blockedByUidRules;
2762 }
Maciej Żenczykowskia08692f2024-04-11 19:49:28 +00002763 } else {
2764 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2765 }
paulhu7aeba372020-12-30 00:42:19 +08002766 } finally {
2767 Binder.restoreCallingIdentity(ident);
2768 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002769 }
2770
Tommy Webba0dad0a2023-02-20 14:10:55 -05002771 /** Check if UID is currently disallowed general network access based on policies. */
2772 private boolean isUidCurrentlyDisallowedByPolicy(int uid) {
2773 return mLastDisallowedUidsDenylist.contains(uid);
2774 }
2775
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002776 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002777 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2778 return;
2779 }
Hugo Benichi47011212017-03-30 10:46:05 +09002780 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002781 synchronized (mBlockedAppUids) {
2782 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002783 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002784 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002785 blocked = false;
2786 } else {
2787 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002788 }
2789 }
Hugo Benichi47011212017-03-30 10:46:05 +09002790 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2791 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2792 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002793 }
2794
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002795 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002796 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2797 return;
2798 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002799 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002800 final int requestId = nri.getActiveRequest() != null
2801 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002802 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002803 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002804 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002805 }
2806
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002807 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002808 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002809 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002810 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002811 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002812 @NonNull
2813 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2814 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002815 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2816 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2817 // but only exists if an app asks about them or requests them. Ensure the requesting app
2818 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002819 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002820 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2821 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2822 null /* extraInfo */);
2823 }
2824 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002825 return filtered;
2826 }
2827
2828 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2829 boolean ignoreBlocked) {
2830 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2831 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002832 }
2833
2834 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002835 * Return NetworkInfo for the active (i.e., connected) network interface.
2836 * It is assumed that at most one network is active at a time. If more
2837 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002838 * @return the info for the active network, or {@code null} if none is
2839 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002840 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002841 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002842 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002843 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002844 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002845 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002846 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2847 if (nai == null) return null;
Motomu Utsumib15be222024-05-15 18:50:08 +09002848 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false /* ignoreBlocked */);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002849 maybeLogBlockedNetworkInfo(networkInfo, uid);
2850 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002851 }
2852
Paul Jensen1f567382015-02-13 14:18:39 -05002853 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002854 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002855 public Network getActiveNetwork() {
2856 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002857 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002858 }
2859
2860 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002861 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002862 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002863 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002864 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002865 }
2866
Chalard Jean46bfbf02022-02-02 00:56:25 +09002867 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002868 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Tommy Webba0dad0a2023-02-20 14:10:55 -05002869 return getActiveNetworkForUidInternal(getVpnForUid(uid), uid, ignoreBlocked);
2870 }
2871
2872 private Network getActiveNetworkOrConnectingVpnForUidInternal(final int uid,
2873 boolean ignoreBlocked) {
2874 return getActiveNetworkForUidInternal(
2875 getConnectedOrConnectingVpnForUid(uid), uid, ignoreBlocked);
2876 }
2877
2878 private Network getActiveNetworkForUidInternal(final NetworkAgentInfo vpnNai,
2879 final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002880 if (vpnNai != null) {
2881 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2882 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2883 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002884 }
Paul Jensen1f567382015-02-13 14:18:39 -05002885 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002886
James Mattis2516da32021-01-31 17:06:19 -08002887 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002888 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2889 ignoreBlocked)) {
2890 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002891 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002892 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002893 }
2894
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002895 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002896 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002897 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002898 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002899 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2900 if (nai == null) return null;
2901 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002902 }
2903
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002904 /** Returns a NetworkInfo object for a network that doesn't exist. */
2905 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2906 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2907 getNetworkTypeName(networkType), "" /* subtypeName */);
2908 info.setIsAvailable(true);
2909 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2910 // background data is restricted.
2911 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2912 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2913 ? DetailedState.BLOCKED
2914 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002915 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2916 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002917 return info;
2918 }
2919
Lorenzo Colittia7574052021-01-19 01:33:05 +09002920 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002921 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2922 return null;
2923 }
2924 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002925 if (nai == null) {
2926 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002927 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002928 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2929 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002930 }
2931
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002932 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002933 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002934 public NetworkInfo getNetworkInfo(int networkType) {
2935 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002936 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002937 if (getVpnUnderlyingNetworks(uid) != null) {
2938 // A VPN is active, so we may need to return one of its underlying networks. This
2939 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002940 // getNetworkAgentInfoForUid.
2941 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2942 if (nai == null) return null;
2943 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2944 if (networkInfo.getType() == networkType) {
2945 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002946 }
2947 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002948 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002949 }
2950
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002951 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002952 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002953 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002954 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002955 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002956 if (nai == null) return null;
2957 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002958 }
2959
2960 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002961 public NetworkInfo[] getAllNetworkInfo() {
2962 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002963 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002964 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2965 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002966 NetworkInfo info = getNetworkInfo(networkType);
2967 if (info != null) {
2968 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002969 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002970 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002971 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002972 }
2973
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002974 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002975 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002976 public Network getNetworkForType(int networkType) {
2977 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002978 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2979 return null;
2980 }
2981 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2982 if (nai == null) {
2983 return null;
2984 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002985 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002986 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2987 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002988 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002989 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002990 }
2991
2992 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002993 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002994 public Network[] getAllNetworks() {
2995 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002996 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002997 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002998 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002999 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003000 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04003001 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003002 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003003 }
3004
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09003005 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08003006 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08003007 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09003008 // The basic principle is: if an app's traffic could possibly go over a
3009 // network, without the app doing anything multinetwork-specific,
3010 // (hence, by "default"), then include that network's capabilities in
3011 // the array.
3012 //
3013 // In the normal case, app traffic only goes over the system's default
3014 // network connection, so that's the only network returned.
3015 //
3016 // With a VPN in force, some app traffic may go into the VPN, and thus
3017 // over whatever underlying networks the VPN specifies, while other app
3018 // traffic may go over the system default network (e.g.: a split-tunnel
3019 // VPN, or an app disallowed by the VPN), so the set of networks
3020 // returned includes the VPN's underlying networks and the system
3021 // default.
3022 enforceAccessPermission();
3023
Chalard Jeand6c33dc2018-06-04 13:33:12 +09003024 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09003025
James Mattis2516da32021-01-31 17:06:19 -08003026 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
3027 if (!nri.isBeingSatisfied()) {
3028 continue;
3029 }
3030 final NetworkAgentInfo nai = nri.getSatisfier();
3031 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
3032 if (null != nc
3033 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
3034 && !result.containsKey(nai.network)) {
3035 result.put(
3036 nai.network,
3037 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08003038 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08003039 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
3040 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08003041 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09003042 }
3043
Lorenzo Colittidfab3032020-12-15 00:49:41 +09003044 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09003045 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08003046 if (null != networks) {
3047 for (final Network network : networks) {
3048 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
3049 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08003050 result.put(
3051 network,
3052 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08003053 nc,
3054 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08003055 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08003056 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09003057 }
3058 }
3059 }
3060
3061 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
3062 out = result.values().toArray(out);
3063 return out;
3064 }
3065
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003066 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
3067 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
3068 // can call sampleConnectivityState and make the checks on it.
3069 @NonNull
3070 private StatsEvent sampleConnectivityStateToStatsEvent() {
3071 final ConnectivityStateSample sample = sampleConnectivityState();
3072 return ConnectivityStatsLog.buildStatsEvent(
3073 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
3074 sample.getNetworkCountPerTransports().toByteArray(),
3075 sample.getConnectionDurationPerTransports().toByteArray(),
3076 sample.getNetworkRequestCount().toByteArray(),
3077 sample.getNetworks().toByteArray());
3078 }
3079
3080 /**
3081 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
3082 *
3083 * This is used for metrics. These snapshots will be sampled and constitute a base for
3084 * statistics about connectivity state of devices.
3085 */
3086 @VisibleForTesting
3087 @NonNull
3088 public ConnectivityStateSample sampleConnectivityState() {
3089 ensureRunningOnConnectivityServiceThread();
3090 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
3091 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
3092 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
3093 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
3094 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
3095 return builder.build();
3096 }
3097
3098 private static NetworkCountPerTransports sampleNetworkCount(
3099 @NonNull final ArraySet<NetworkAgentInfo> nais) {
3100 final SparseIntArray countPerTransports = new SparseIntArray();
3101 for (final NetworkAgentInfo nai : nais) {
3102 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
3103 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
3104 }
3105 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
3106 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
3107 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
3108 c.setTransportTypes(countPerTransports.keyAt(i));
3109 c.setNetworkCount(countPerTransports.valueAt(i));
3110 builder.addNetworkCountForTransports(c);
3111 }
3112 return builder.build();
3113 }
3114
3115 private static ConnectionDurationPerTransports sampleConnectionDuration(
3116 @NonNull final ArraySet<NetworkAgentInfo> nais) {
3117 final ConnectionDurationPerTransports.Builder builder =
3118 ConnectionDurationPerTransports.newBuilder();
3119 for (final NetworkAgentInfo nai : nais) {
3120 final ConnectionDurationForTransports.Builder c =
3121 ConnectionDurationForTransports.newBuilder();
3122 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
3123 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
3124 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
3125 // Add millisPerSecond/2 to round up or down to the nearest value
3126 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
3127 builder.addConnectionDurationForTransports(c);
3128 }
3129 return builder.build();
3130 }
3131
3132 private static NetworkRequestCount sampleNetworkRequestCount(
3133 @NonNull final Collection<NetworkRequestInfo> nris) {
3134 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
3135 final SparseIntArray countPerType = new SparseIntArray();
3136 for (final NetworkRequestInfo nri : nris) {
3137 final int type;
3138 if (Process.SYSTEM_UID == nri.mAsUid) {
3139 // The request is filed "as" the system, so it's the system on its own behalf.
3140 type = RequestType.RT_SYSTEM.getNumber();
3141 } else if (Process.SYSTEM_UID == nri.mUid) {
3142 // The request is filed by the system as some other app, so it's the system on
3143 // behalf of an app.
3144 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
3145 } else {
3146 // Not the system, so it's an app requesting on its own behalf.
3147 type = RequestType.RT_APP.getNumber();
3148 }
Motomu Utsumie08de4d2024-02-28 15:58:42 +09003149 countPerType.put(type, countPerType.get(type, 0) + 1);
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003150 }
3151 for (int i = countPerType.size() - 1; i >= 0; --i) {
3152 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
3153 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
3154 r.setRequestCount(countPerType.valueAt(i));
3155 builder.addRequestCountForType(r);
3156 }
3157 return builder.build();
3158 }
3159
3160 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
3161 final NetworkList.Builder builder = NetworkList.newBuilder();
3162 for (final NetworkAgentInfo nai : nais) {
3163 final NetworkCapabilities nc = nai.networkCapabilities;
3164 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
3165 d.setTransportTypes((int) nc.getTransportTypesInternal());
3166 final MeteredState meteredState;
3167 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
3168 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
3169 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
3170 meteredState = MeteredState.METERED_NO;
3171 } else {
3172 meteredState = MeteredState.METERED_YES;
3173 }
3174 d.setMeteredState(meteredState);
3175 final ValidatedState validatedState;
3176 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3177 validatedState = ValidatedState.VS_PORTAL;
3178 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
3179 validatedState = ValidatedState.VS_PARTIAL;
3180 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
3181 validatedState = ValidatedState.VS_VALID;
3182 } else {
3183 validatedState = ValidatedState.VS_INVALID;
3184 }
3185 d.setValidatedState(validatedState);
3186 d.setScorePolicies(nai.getScore().getPoliciesInternal());
3187 d.setCapabilities(nc.getCapabilitiesInternal());
3188 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
3189 builder.addNetworkDescription(d);
3190 }
3191 return builder.build();
3192 }
3193
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003194 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003195 public boolean isNetworkSupported(int networkType) {
3196 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003197 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07003198 }
3199
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07003200 /**
3201 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08003202 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07003203 * @return the ip properties for the active network, or {@code null} if
3204 * none is active
3205 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003206 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07003207 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003208 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003209 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09003210 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
3211 if (nai == null) return null;
3212 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003213 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07003214 }
3215
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003216 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003217 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07003218 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003219 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003220 final LinkProperties lp = getLinkProperties(nai);
3221 if (lp == null) return null;
3222 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003223 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07003224 }
3225
Robert Greenwaltbe46b752014-05-13 21:41:06 -07003226 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07003227 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003228 public LinkProperties getLinkProperties(Network network) {
3229 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003230 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
3231 if (lp == null) return null;
3232 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003233 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09003234 }
3235
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003236 @Nullable
3237 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09003238 if (nai == null) {
3239 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003240 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09003241 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003242 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09003243 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003244 }
3245
lucaslinc582d502022-01-27 09:07:00 +08003246 @Override
3247 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08003248 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08003249 @NonNull String packageName, @Nullable String callingAttributionTag) {
3250 Objects.requireNonNull(packageName);
3251 Objects.requireNonNull(lp);
3252 enforceNetworkStackOrSettingsPermission();
Junyu Lai71b51532024-02-01 10:39:01 +08003253 if (!hasAccessPermission(-1 /* pid */, uid)) {
lucaslinc582d502022-01-27 09:07:00 +08003254 return null;
3255 }
3256 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
3257 }
3258
Qingxi Lib2748102020-01-08 12:51:49 -08003259 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
3260 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
3261 }
3262
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003263 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003264 if (nai == null) return null;
3265 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003266 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003267 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003268 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003269 }
3270
3271 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08003272 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
3273 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003274 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003275 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08003276 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08003277 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08003278 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08003279 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003280 }
3281
lucaslinc582d502022-01-27 09:07:00 +08003282 @Override
lucaslind2b06132022-03-02 10:56:57 +08003283 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
3284 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
3285 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08003286 Objects.requireNonNull(nc);
3287 Objects.requireNonNull(packageName);
3288 enforceNetworkStackOrSettingsPermission();
Junyu Lai71b51532024-02-01 10:39:01 +08003289 if (!hasAccessPermission(-1 /* pid */, uid)) {
lucaslinc582d502022-01-27 09:07:00 +08003290 return null;
3291 }
3292 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
3293 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
3294 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
3295 callingAttributionTag);
3296 }
3297
lucaslin69e1aa92022-03-22 18:15:09 +08003298 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
3299 if (nc.getUnderlyingNetworks() != null
Junyu Lai71b51532024-02-01 10:39:01 +08003300 && !hasNetworkFactoryOrSettingsPermission(pid, uid)) {
lucaslin69e1aa92022-03-22 18:15:09 +08003301 nc.setUnderlyingNetworks(null);
3302 }
3303 }
3304
Chalard Jean53017782022-11-24 17:13:44 +09003305 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
3306 return Process.SYSTEM_UID == uid
Ying Xu611b8042024-02-27 10:07:43 -08003307 || netOwnerUid == uid
Junyu Lai71b51532024-02-01 10:39:01 +08003308 || hasAnyPermissionOf(mContext, pid, uid,
Chalard Jean53017782022-11-24 17:13:44 +09003309 android.Manifest.permission.NETWORK_FACTORY);
3310 }
3311
Qingxi Libb8da982020-01-17 17:54:27 -08003312 @VisibleForTesting
3313 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09003314 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08003315 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
3316 // this would be expensive (one more permission check every time any NC callback is
3317 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
3318 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
3319 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09003320 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Junyu Lai71b51532024-02-01 10:39:01 +08003321 if (!hasSettingsPermission(callerPid, callerUid)) {
Chalard Jean46adcf32018-04-18 20:18:38 +09003322 newNc.setUids(null);
3323 newNc.setSSID(null);
3324 }
Etan Cohen107ae952018-12-30 17:59:59 -08003325 if (newNc.getNetworkSpecifier() != null) {
3326 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
3327 }
Junyu Lai71b51532024-02-01 10:39:01 +08003328 if (!hasAnyPermissionOf(mContext, callerPid, callerUid,
Junyu Lai4c6fe232023-04-11 11:33:46 +08003329 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07003330 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
3331 newNc.setAdministratorUids(new int[0]);
3332 }
Chalard Jean53017782022-11-24 17:13:44 +09003333 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09003334 newNc.setAllowedUids(new ArraySet<>());
Benedict Wong53de25f2021-03-24 14:01:51 -07003335 }
lucaslin69e1aa92022-03-22 18:15:09 +08003336 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08003337
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09003338 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09003339 }
3340
Roshan Pius98f59ec2021-02-23 08:47:39 -08003341 /**
3342 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08003343 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08003344 * NetworkCapabilities.
3345 * Note: This wrapper does not support any sort of invalidation and thus must not be
3346 * persistent or long-lived. It may only be used for the time necessary to
3347 * compute the redactions required by one particular NetworkCallback or
3348 * synchronous call.
3349 */
3350 private class RedactionPermissionChecker {
3351 private final int mCallingPid;
3352 private final int mCallingUid;
3353 @NonNull private final String mCallingPackageName;
3354 @Nullable private final String mCallingAttributionTag;
3355
3356 private Boolean mHasLocationPermission = null;
3357 private Boolean mHasLocalMacAddressPermission = null;
3358 private Boolean mHasSettingsPermission = null;
3359
3360 RedactionPermissionChecker(int callingPid, int callingUid,
3361 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
3362 mCallingPid = callingPid;
3363 mCallingUid = callingUid;
3364 mCallingPackageName = callingPackageName;
3365 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08003366 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08003367
3368 private boolean hasLocationPermissionInternal() {
3369 final long token = Binder.clearCallingIdentity();
3370 try {
3371 return mLocationPermissionChecker.checkLocationPermission(
3372 mCallingPackageName, mCallingAttributionTag, mCallingUid,
3373 null /* message */);
3374 } finally {
3375 Binder.restoreCallingIdentity(token);
3376 }
3377 }
3378
3379 /**
3380 * Returns whether the app holds location permission or not (might return cached result
3381 * if the permission was already checked before).
3382 */
3383 public boolean hasLocationPermission() {
3384 if (mHasLocationPermission == null) {
3385 // If there is no cached result, perform the check now.
3386 mHasLocationPermission = hasLocationPermissionInternal();
3387 }
3388 return mHasLocationPermission;
3389 }
3390
3391 /**
3392 * Returns whether the app holds local mac address permission or not (might return cached
3393 * result if the permission was already checked before).
3394 */
Junyu Lai71b51532024-02-01 10:39:01 +08003395 @CheckResult
Roshan Pius98f59ec2021-02-23 08:47:39 -08003396 public boolean hasLocalMacAddressPermission() {
3397 if (mHasLocalMacAddressPermission == null) {
3398 // If there is no cached result, perform the check now.
Junyu Lai71b51532024-02-01 10:39:01 +08003399 mHasLocalMacAddressPermission = ConnectivityService.this
3400 .hasLocalMacAddressPermission(mCallingPid, mCallingUid);
Roshan Pius98f59ec2021-02-23 08:47:39 -08003401 }
3402 return mHasLocalMacAddressPermission;
3403 }
3404
3405 /**
3406 * Returns whether the app holds settings permission or not (might return cached
3407 * result if the permission was already checked before).
3408 */
Junyu Lai71b51532024-02-01 10:39:01 +08003409 @CheckResult
Roshan Pius98f59ec2021-02-23 08:47:39 -08003410 public boolean hasSettingsPermission() {
3411 if (mHasSettingsPermission == null) {
3412 // If there is no cached result, perform the check now.
Junyu Lai71b51532024-02-01 10:39:01 +08003413 mHasSettingsPermission =
3414 ConnectivityService.this.hasSettingsPermission(mCallingPid, mCallingUid);
Roshan Pius98f59ec2021-02-23 08:47:39 -08003415 }
3416 return mHasSettingsPermission;
3417 }
3418 }
3419
3420 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
3421 @NetworkCapabilities.NetCapability long redaction) {
3422 return (redactions & redaction) != 0;
3423 }
3424
3425 /**
3426 * Use the provided |applicableRedactions| to check the receiving app's
3427 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
3428 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
3429 * before being sent to the corresponding app.
3430 */
3431 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
3432 @NetworkCapabilities.RedactionType long applicableRedactions,
3433 @NonNull RedactionPermissionChecker redactionPermissionChecker,
3434 boolean includeLocationSensitiveInfo) {
3435 long redactions = applicableRedactions;
3436 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
3437 if (includeLocationSensitiveInfo
3438 && redactionPermissionChecker.hasLocationPermission()) {
3439 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
3440 }
3441 }
3442 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
3443 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
3444 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
3445 }
3446 }
3447 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
3448 if (redactionPermissionChecker.hasSettingsPermission()) {
3449 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
3450 }
3451 }
3452 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08003453 }
3454
Qingxi Lib2748102020-01-08 12:51:49 -08003455 @VisibleForTesting
3456 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08003457 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08003458 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08003459 int callingPid, int callingUid, @NonNull String callingPkgName,
3460 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08003461 if (nc == null) {
3462 return null;
3463 }
Roshan Pius9ed14622020-12-28 09:01:49 -08003464 // Avoid doing location permission check if the transport info has no location sensitive
3465 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08003466 final RedactionPermissionChecker redactionPermissionChecker =
3467 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
3468 callingAttributionTag);
3469 final long redactions = retrieveRequiredRedactions(
3470 nc.getApplicableRedactions(), redactionPermissionChecker,
3471 includeLocationSensitiveInfo);
3472 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08003473 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08003474 // TODO : calling UID is redacted because apps should generally not know what UID is
3475 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08003476 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08003477 newNc.setOwnerUid(INVALID_UID);
3478 return newNc;
3479 }
Benedict Wongbf004e92020-06-08 11:55:38 -07003480 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
3481 if (nc.hasTransport(TRANSPORT_VPN)) {
3482 // Owner UIDs already checked above. No need to re-check.
3483 return newNc;
3484 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08003485 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
3486 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08003487 // compatibility for older apps.
3488 if (!includeLocationSensitiveInfo
3489 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08003490 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08003491 newNc.setOwnerUid(INVALID_UID);
3492 return newNc;
3493 }
Roshan Pius9ed14622020-12-28 09:01:49 -08003494 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08003495 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08003496 newNc.setOwnerUid(INVALID_UID);
3497 }
Qingxi Lib2748102020-01-08 12:51:49 -08003498 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08003499 }
3500
lucaslinc582d502022-01-27 09:07:00 +08003501 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003502 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
3503 LinkProperties lp, int callerPid, int callerUid) {
3504 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08003505 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
3506 // this would be expensive (one more permission check every time any LP callback is
3507 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
3508 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
3509 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003510
3511 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
3512 final boolean needsSanitization =
3513 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
3514 if (!needsSanitization) {
3515 return new LinkProperties(lp);
3516 }
3517
Junyu Lai71b51532024-02-01 10:39:01 +08003518 if (hasSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09003519 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003520 }
3521
3522 final LinkProperties newLp = new LinkProperties(lp);
3523 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
3524 // object gets parceled.
3525 newLp.setCaptivePortalApiUrl(null);
3526 newLp.setCaptivePortalData(null);
3527 return newLp;
3528 }
3529
Roshan Pius08c94fb2020-01-16 12:17:17 -08003530 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
3531 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003532 // There is no need to track the effective UID of the request here. If the caller
3533 // lacks the settings permission, the effective UID is the same as the calling ID.
Junyu Lai71b51532024-02-01 10:39:01 +08003534 if (!hasSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003535 // Unprivileged apps can only pass in null or their own UID.
3536 if (nc.getUids() == null) {
3537 // If the caller passes in null, the callback will also match networks that do not
3538 // apply to its UID, similarly to what it would see if it called getAllNetworks.
3539 // In this case, redact everything in the request immediately. This ensures that the
3540 // app is not able to get any redacted information by filing an unredacted request
3541 // and observing whether the request matches something.
3542 if (nc.getNetworkSpecifier() != null) {
3543 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
3544 }
3545 } else {
3546 nc.setSingleUid(callerUid);
3547 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09003548 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08003549 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07003550 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08003551
3552 // Clear owner UID; this can never come from an app.
3553 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003554 }
3555
Chalard Jean38354d12018-03-20 19:13:57 +09003556 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003557 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09003558 nc.addCapability(NET_CAPABILITY_FOREGROUND);
3559 }
3560 }
3561
Motomu Utsumiad480e02024-01-30 16:21:51 +09003562 private void maybeDisableLocalNetworkMatching(NetworkCapabilities nc, int callingUid) {
Junyu Lai0b806fd2025-03-19 07:30:11 +08003563 // If disabled, NetworkRequest cannot match non-thread local networks even if
3564 // specified explicitly. Compat change is enabled by default on apps targeting B+.
3565 // Agent should not be visible on U- even if it's rolled out.
3566 nc.setMatchNonThreadLocalNetworks(mDeps.isAtLeastV() && mDeps.isChangeEnabled(
3567 ENABLE_MATCH_NON_THREAD_LOCAL_NETWORKS, callingUid));
Motomu Utsumiad480e02024-01-30 16:21:51 +09003568 if (mDeps.isChangeEnabled(ENABLE_MATCH_LOCAL_NETWORK, callingUid)) {
3569 return;
3570 }
3571 // If NET_CAPABILITY_LOCAL_NETWORK is not added to capability, request should not be
3572 // satisfied by local networks.
3573 if (!nc.hasCapability(NET_CAPABILITY_LOCAL_NETWORK)) {
3574 nc.addForbiddenCapability(NET_CAPABILITY_LOCAL_NETWORK);
3575 }
3576 }
3577
3578 private void restrictRequestNetworkCapabilitiesForCaller(NetworkCapabilities nc,
3579 int callingUid, String callerPackageName) {
3580 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callerPackageName);
3581 maybeDisableLocalNetworkMatching(nc, callingUid);
3582 }
3583
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09003584 @Override
3585 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
3586 enforceAccessPermission();
3587 final int callerUid = Binder.getCallingUid();
3588 final long token = Binder.clearCallingIdentity();
3589 try {
3590 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
3591 } finally {
3592 Binder.restoreCallingIdentity(token);
3593 }
3594 }
3595
junyulaiebd15162021-03-03 12:09:05 +08003596 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003597 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07003598 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08003599 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08003600 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08003601
Serik Beketayev05130302021-01-15 16:47:25 -08003602 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08003603 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08003604 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
3605 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08003606 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08003607 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08003608 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08003609 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
3610 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07003611 }
3612 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09003613 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07003614 }
3615
Jeff Sharkey66fa9682011-08-02 17:22:34 -07003616 @Override
junyulaiebd15162021-03-03 12:09:05 +08003617 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08003618 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08003619 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08003620 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08003621
3622 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
3623 for (Network network : getAllNetworks()) {
3624 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09003625 final boolean includeNetwork = (nai != null) && nai.isCreated();
3626 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08003627 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
3628 // NetworkCapabilities, which may contain UIDs of apps to which the
3629 // network applies. Should the UIDs be cleared so as not to leak or
3630 // interfere ?
3631 result.add(nai.getNetworkStateSnapshot());
3632 }
3633 }
3634 return result;
3635 }
3636
3637 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003638 public boolean isActiveNetworkMetered() {
3639 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003640
Qingxi Lib2748102020-01-08 12:51:49 -08003641 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06003642 if (caps != null) {
3643 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3644 } else {
3645 // Always return the most conservative value
3646 return true;
3647 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07003648 }
3649
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003650 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09003651 * Ensures that the system cannot call a particular method.
3652 */
3653 private boolean disallowedBecauseSystemCaller() {
3654 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07003655 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
3656 // for devices launched with Q and above. However, existing devices upgrading to Q and
3657 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003658 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07003659 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003660 log("This method exists only for app backwards compatibility"
3661 + " and must not be called by system services.");
3662 return true;
3663 }
3664 return false;
3665 }
3666
3667 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003668 * Ensure that a network route exists to deliver traffic to the specified
3669 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003670 * @param networkType the type of the network over which traffic to the
3671 * specified host is to be routed
3672 * @param hostAddress the IP address of the host to which the route is
3673 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003674 * @return {@code true} on success, {@code false} on failure
3675 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003676 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003677 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3678 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003679 if (disallowedBecauseSystemCaller()) {
3680 return false;
3681 }
Junyu Lai8fdc4312024-01-16 11:19:43 +08003682 PermissionUtils.enforcePackageNameMatchesUid(
3683 mContext, mDeps.getCallingUid(), callingPackageName);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003684 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003685 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003686 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003687 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003688
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003689 InetAddress addr;
3690 try {
3691 addr = InetAddress.getByAddress(hostAddress);
3692 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003693 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003694 return false;
3695 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003696
The Android Open Source Project28527d22009-03-03 19:31:44 -08003697 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003698 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003699 return false;
3700 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003701
3702 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3703 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003704 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003705 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3706 } else {
3707 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3708 }
3709 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003710 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003711
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003712 DetailedState netState;
3713 synchronized (nai) {
3714 netState = nai.networkInfo.getDetailedState();
3715 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003716
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003717 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003718 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003719 log("requestRouteToHostAddress on down network "
3720 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003721 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003722 }
3723 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003724 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003725
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003726 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003727 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003728 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003729 LinkProperties lp;
3730 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003731 synchronized (nai) {
3732 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003733 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003734 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003735 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003736 if (DBG) {
3737 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3738 }
Wink Saville32506bc2013-06-29 21:10:57 -07003739 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003740 } finally {
3741 Binder.restoreCallingIdentity(token);
3742 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003743 }
3744
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003745 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003746 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003747 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003748 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003749 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003750 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003751 if (bestRoute.getGateway().equals(addr)) {
3752 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003753 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003754 } else {
3755 // if we will connect to this through another route, add a direct route
3756 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003757 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003758 }
3759 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003760 if (DBG) log("Adding legacy route " + bestRoute +
3761 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003762
3763 final String dst = bestRoute.getDestinationLinkAddress().toString();
3764 final String nextHop = bestRoute.hasGateway()
3765 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003766 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003767 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3768 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003769 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003770 return false;
3771 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003772 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003773 }
3774
paulhu7c0a2e62021-01-08 00:51:49 +08003775 class DnsResolverUnsolicitedEventCallback extends
3776 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003777 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003778 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003779 try {
3780 mHandler.sendMessage(mHandler.obtainMessage(
3781 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003782 new PrivateDnsValidationUpdate(event.netId,
3783 InetAddresses.parseNumericAddress(event.ipAddress),
3784 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003785 } catch (IllegalArgumentException e) {
3786 loge("Error parsing ip address in validation event");
3787 }
3788 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003789
3790 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003791 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3792 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003793 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3794 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3795 // event callback for certain nai. e.g. cellular. Register here to pass to
3796 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003797 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003798 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3799 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003800 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003801 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003802 }
3803 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003804
3805 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003806 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3807 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3808 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003809 }
dalyk1720e542018-03-05 12:42:22 -05003810
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003811 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003812 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003813 return this.VERSION;
3814 }
3815
3816 @Override
3817 public String getInterfaceHash() {
3818 return this.HASH;
3819 }
paulhu7c0a2e62021-01-08 00:51:49 +08003820 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003821
3822 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003823 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3824 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003825
paulhu7c0a2e62021-01-08 00:51:49 +08003826 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003827 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003828 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003829 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003830 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003831 }
3832 }
3833
Sudheer Shanka9967d462021-03-18 19:09:25 +00003834 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003835 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003836 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Motomu Utsumid20727f2024-05-23 21:44:40 +09003837 if (shouldTrackUidsForBlockedStatusCallbacks()) {
3838 Log.wtf(TAG, "Received unexpected NetworkPolicy callback");
3839 return;
3840 }
3841 mHandler.sendMessage(mHandler.obtainMessage(
3842 EVENT_BLOCKED_REASONS_CHANGED,
3843 List.of(new Pair<>(uid, blockedReasons))));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003844 }
Tommy Webba0dad0a2023-02-20 14:10:55 -05003845
3846 @Override
3847 public void onUidsAllowedTransportsChanged(int[] uids, long[] allowedTransports) {
3848 setUidsAllowedTransports(uids, allowedTransports);
3849 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003850 };
3851
Motomu Utsumid20727f2024-05-23 21:44:40 +09003852 private boolean shouldTrackUidsForBlockedStatusCallbacks() {
3853 return mDeps.isAtLeastV();
3854 }
3855
3856 @VisibleForTesting
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +09003857 public void handleBlockedReasonsChanged(List<Pair<Integer, Integer>> reasonsList) {
Motomu Utsumid20727f2024-05-23 21:44:40 +09003858 for (Pair<Integer, Integer> reasons: reasonsList) {
3859 final int uid = reasons.first;
3860 final int blockedReasons = reasons.second;
3861 if (shouldTrackUidsForBlockedStatusCallbacks()) {
3862 synchronized (mBlockedStatusTrackingUids) {
3863 if (mBlockedStatusTrackingUids.get(uid) == 0) {
3864 // This uid is not tracked anymore.
3865 // This can happen if the network request is unregistered while
3866 // EVENT_BLOCKED_REASONS_CHANGED is posted but not processed yet.
3867 continue;
3868 }
3869 }
3870 }
3871 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
3872 setUidBlockedReasons(uid, blockedReasons);
3873 }
junyulaif2c67e42018-08-07 19:50:45 +08003874 }
3875
Mark Fasheh7c999d82023-05-04 20:23:11 +00003876 static final class UidFrozenStateChangedArgs {
3877 final int[] mUids;
3878 final int[] mFrozenStates;
3879
3880 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3881 mUids = uids;
3882 mFrozenStates = frozenStates;
3883 }
3884 }
3885
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003886 /**
3887 * Check if the cell network is idle.
3888 * @return true if the cell network state is idle
3889 * false if the cell network state is active or unknown
3890 */
3891 private boolean isCellNetworkIdle() {
3892 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3893 if (defaultNai == null
3894 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3895 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3896 // cell network is not the default network, cell network state is unknown.
3897 // TODO(b/279380356): Track cell network state when the cell is not the default network
3898 return false;
3899 }
3900
3901 return !mNetworkActivityTracker.isDefaultNetworkActive();
3902 }
3903
Motomu Utsumiff555a72024-05-23 23:22:40 +09003904 private boolean shouldTrackFirewallDestroySocketReasons() {
3905 return mDeps.isAtLeastV();
3906 }
3907
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09003908 private void updateDestroySocketReasons(final int uid, final int reason,
3909 final boolean addReason) {
3910 final int destroyReasons = mDestroySocketPendingUids.get(uid, DESTROY_SOCKET_REASON_NONE);
3911 if (addReason) {
3912 mDestroySocketPendingUids.put(uid, destroyReasons | reason);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003913 } else {
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09003914 final int newDestroyReasons = destroyReasons & ~reason;
3915 if (newDestroyReasons == DESTROY_SOCKET_REASON_NONE) {
3916 mDestroySocketPendingUids.delete(uid);
3917 } else {
3918 mDestroySocketPendingUids.put(uid, newDestroyReasons);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003919 }
3920 }
3921 }
3922
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09003923 private void handleFrozenUids(int[] uids, int[] frozenStates) {
3924 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN48d25272024-07-03 18:50:03 +09003925 handleDestroyFrozenSockets(uids, frozenStates);
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +09003926 handleFreezeNetworkCallbacks(uids, frozenStates);
Remi NGUYEN VAN48d25272024-07-03 18:50:03 +09003927 }
3928
3929 private void handleDestroyFrozenSockets(int[] uids, int[] frozenStates) {
3930 if (!mDestroyFrozenSockets) {
3931 return;
3932 }
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09003933 for (int i = 0; i < uids.length; i++) {
3934 final int uid = uids[i];
3935 final boolean addReason = frozenStates[i] == UID_FROZEN_STATE_FROZEN;
3936 updateDestroySocketReasons(uid, DESTROY_SOCKET_REASON_FROZEN, addReason);
3937 }
3938
3939 if (!mDelayDestroySockets || !isCellNetworkIdle()) {
3940 destroyPendingSockets();
3941 }
3942 }
3943
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +09003944 private void handleFreezeNetworkCallbacks(int[] uids, int[] frozenStates) {
3945 if (!mQueueCallbacksForFrozenApps) {
3946 return;
3947 }
3948 for (int i = 0; i < uids.length; i++) {
3949 final int uid = uids[i];
3950 // These counters may be modified on different threads, but using them here is fine
3951 // because this is only an optimization where wrong behavior would only happen if they
3952 // are zero even though there is a request registered. This is not possible as they are
3953 // always incremented before posting messages to register, and decremented on the
3954 // handler thread when unregistering.
3955 if (mSystemNetworkRequestCounter.get(uid) == 0
3956 && mNetworkRequestCounter.get(uid) == 0) {
3957 // Avoid iterating requests if there isn't any. The counters only track app requests
3958 // and not internal requests (for example always-on requests which do not have a
3959 // mMessenger), so it does not completely match the content of mRequests. This is OK
3960 // as only app requests need to be frozen.
3961 continue;
3962 }
3963
3964 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
3965 freezeNetworkCallbacksForUid(uid);
3966 } else {
3967 unfreezeNetworkCallbacksForUid(uid);
3968 }
3969 }
3970 }
3971
3972 /**
3973 * Suspend callbacks for a UID that was just frozen.
3974 *
3975 * <p>Note that it is not possible for a process to be frozen during a blocking binder call
3976 * (see CachedAppOptimizer.freezeBinder), and IConnectivityManager callback registrations are
3977 * blocking binder calls, so no callback can be registered while the UID is frozen. This means
3978 * it is not necessary to check frozen state on new callback registrations, and calling this
3979 * method when a UID is newly frozen is sufficient.
3980 *
3981 * <p>If it ever becomes possible for a process to be frozen during a blocking binder call,
3982 * ConnectivityService will need to handle freezing callbacks that reach ConnectivityService
3983 * after the app was frozen when being registered.
3984 */
3985 private void freezeNetworkCallbacksForUid(int uid) {
3986 if (DDBG) Log.d(TAG, "Freezing callbacks for UID " + uid);
3987 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3988 if (nri.mUid != uid) continue;
3989 // mNetworkRequests can have duplicate values for multilayer requests, but calling
3990 // onFrozen multiple times is fine.
3991 // If freezeNetworkCallbacksForUid was called multiple times in a raw for a frozen UID
3992 // (which would be incorrect), this would also handle it gracefully.
3993 nri.onFrozen();
3994 }
3995 }
3996
3997 private void unfreezeNetworkCallbacksForUid(int uid) {
3998 // This sends all callbacks for one NetworkRequest at a time, which may not be the
3999 // same order they were queued in, but different network requests use different
4000 // binder objects, so the relative order of their callbacks is not guaranteed.
4001 // If callbacks are not queued, callbacks from different binder objects may be
4002 // posted on different threads when the process is unfrozen, so even if they were
4003 // called a long time apart while the process was frozen, they may still appear in
4004 // different order when unfreezing it.
4005 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4006 if (nri.mUid != uid) continue;
4007 nri.sendQueuedCallbacks();
4008 }
4009 }
4010
Motomu Utsumiff555a72024-05-23 23:22:40 +09004011 private void handleUpdateFirewallDestroySocketReasons(
4012 List<Pair<Integer, Integer>> reasonsList) {
4013 if (!shouldTrackFirewallDestroySocketReasons()) {
4014 Log.wtf(TAG, "handleUpdateFirewallDestroySocketReasons is called unexpectedly");
4015 return;
4016 }
4017 ensureRunningOnConnectivityServiceThread();
4018
4019 for (Pair<Integer, Integer> uidSocketDestroyReasons: reasonsList) {
4020 final int uid = uidSocketDestroyReasons.first;
4021 final int reasons = uidSocketDestroyReasons.second;
4022 final boolean destroyByFirewallBackground =
4023 (reasons & DESTROY_SOCKET_REASON_FIREWALL_BACKGROUND)
4024 != DESTROY_SOCKET_REASON_NONE;
4025 updateDestroySocketReasons(uid, DESTROY_SOCKET_REASON_FIREWALL_BACKGROUND,
4026 destroyByFirewallBackground);
4027 }
4028
4029 if (!mDelayDestroySockets || !isCellNetworkIdle()) {
4030 destroyPendingSockets();
4031 }
4032 }
4033
4034 private void handleClearFirewallDestroySocketReasons(final int reason) {
4035 if (!shouldTrackFirewallDestroySocketReasons()) {
4036 Log.wtf(TAG, "handleClearFirewallDestroySocketReasons is called uexpectedly");
4037 return;
4038 }
4039 ensureRunningOnConnectivityServiceThread();
4040
4041 // Unset reason from all pending uids
4042 for (int i = mDestroySocketPendingUids.size() - 1; i >= 0; i--) {
4043 final int uid = mDestroySocketPendingUids.keyAt(i);
4044 updateDestroySocketReasons(uid, reason, false /* addReason */);
4045 }
4046 }
4047
Motomu Utsumidff5df52024-05-14 18:19:43 +09004048 private void destroyPendingSockets() {
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004049 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09004050 if (mDestroySocketPendingUids.size() == 0) {
Motomu Utsumi333f01d2024-05-14 18:30:31 +09004051 return;
4052 }
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004053
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09004054 Set<Integer> uids = new ArraySet<>();
4055 for (int i = 0; i < mDestroySocketPendingUids.size(); i++) {
4056 uids.add(mDestroySocketPendingUids.keyAt(i));
4057 }
4058
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004059 try {
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09004060 mDeps.destroyLiveTcpSocketsByOwnerUids(uids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004061 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Motomu Utsumidff5df52024-05-14 18:19:43 +09004062 loge("Failed to destroy sockets: " + e);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004063 }
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09004064 mDestroySocketPendingUids.clear();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004065 }
4066
4067 private void handleReportNetworkActivity(final NetworkActivityParams params) {
4068 mNetworkActivityTracker.handleReportNetworkActivity(params);
4069
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09004070 final boolean isCellNetworkActivity;
4071 if (mTrackMultiNetworkActivities) {
4072 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
4073 // nai could be null if netd receives a netlink message and calls the network
4074 // activity change callback after the network is unregistered from ConnectivityService.
4075 isCellNetworkActivity = nai != null
4076 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
4077 } else {
4078 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
4079 }
4080
Motomu Utsumi333f01d2024-05-14 18:30:31 +09004081 if (mDelayDestroySockets && params.isActive && isCellNetworkActivity) {
Motomu Utsumidff5df52024-05-14 18:19:43 +09004082 destroyPendingSockets();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004083 }
4084 }
4085
4086 /**
Motomu Utsumidff5df52024-05-14 18:19:43 +09004087 * If the cellular network is no longer the default network, destroy pending sockets.
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004088 *
4089 * @param newNetwork new default network
4090 * @param oldNetwork old default network
4091 */
Motomu Utsumidff5df52024-05-14 18:19:43 +09004092 private void maybeDestroyPendingSockets(NetworkAgentInfo newNetwork,
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004093 NetworkAgentInfo oldNetwork) {
4094 final boolean isOldNetworkCellular = oldNetwork != null
4095 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
4096 final boolean isNewNetworkCellular = newNetwork != null
4097 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
4098
Motomu Utsumi333f01d2024-05-14 18:30:31 +09004099 if (isOldNetworkCellular && !isNewNetworkCellular) {
Motomu Utsumidff5df52024-05-14 18:19:43 +09004100 destroyPendingSockets();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004101 }
4102 }
4103
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09004104 private void dumpDestroySockets(IndentingPrintWriter pw) {
4105 pw.println("DestroySockets:");
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004106 pw.increaseIndent();
4107 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
Motomu Utsumi390be062024-05-13 17:56:18 +09004108 pw.print("mDelayDestroySockets="); pw.println(mDelayDestroySockets);
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09004109 pw.print("mDestroySocketPendingUids:");
4110 pw.increaseIndent();
4111 for (int i = 0; i < mDestroySocketPendingUids.size(); i++) {
4112 final int uid = mDestroySocketPendingUids.keyAt(i);
4113 final int reasons = mDestroySocketPendingUids.valueAt(i);
4114 pw.print(uid + ": reasons=" + reasons);
4115 }
4116 pw.decreaseIndent();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004117 pw.decreaseIndent();
4118 }
4119
Maciej Żenczykowskif0da1be2024-06-16 05:02:50 -07004120 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Junyu Lai155760b2023-10-05 14:51:00 +08004121 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
4122 pw.println("Bpf Program Status:");
4123 pw.increaseIndent();
4124 try {
4125 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00004126 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08004127 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00004128 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Maciej Żenczykowski22db5902024-05-10 06:44:08 -07004129
Junyu Lai155760b2023-10-05 14:51:00 +08004130 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00004131 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Maciej Żenczykowski22db5902024-05-10 06:44:08 -07004132
Junyu Lai155760b2023-10-05 14:51:00 +08004133 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00004134 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08004135 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00004136 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Maciej Żenczykowski22db5902024-05-10 06:44:08 -07004137
4138 pw.print("CGROUP_INET4_CONNECT: ");
4139 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_CONNECT));
4140 pw.print("CGROUP_INET6_CONNECT: ");
4141 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_CONNECT));
4142
4143 pw.print("CGROUP_UDP4_SENDMSG: ");
4144 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_UDP4_SENDMSG));
4145 pw.print("CGROUP_UDP6_SENDMSG: ");
4146 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_UDP6_SENDMSG));
4147
4148 pw.print("CGROUP_UDP4_RECVMSG: ");
4149 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_UDP4_RECVMSG));
4150 pw.print("CGROUP_UDP6_RECVMSG: ");
4151 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_UDP6_RECVMSG));
4152
4153 pw.print("CGROUP_GETSOCKOPT: ");
4154 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_GETSOCKOPT));
4155 pw.print("CGROUP_SETSOCKOPT: ");
4156 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_SETSOCKOPT));
4157
4158 pw.print("CGROUP_INET_SOCK_RELEASE: ");
4159 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_RELEASE));
Junyu Lai155760b2023-10-05 14:51:00 +08004160 } catch (IOException e) {
4161 pw.println(" IOException");
4162 }
4163 pw.decreaseIndent();
4164 }
4165
Mark Fasheh7c999d82023-05-04 20:23:11 +00004166 @VisibleForTesting
4167 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
4168
Quang Anh Luong28eefef2023-11-07 09:43:41 +09004169 @VisibleForTesting
4170 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
4171 "allow_sysui_connectivity_reports";
4172
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00004173 public static final String ALLOW_SATALLITE_NETWORK_FALLBACK =
4174 "allow_satallite_network_fallback";
4175
Paul Jensen83f5d572014-08-29 09:54:01 -04004176 private void enforceInternetPermission() {
4177 mContext.enforceCallingOrSelfPermission(
4178 android.Manifest.permission.INTERNET,
4179 "ConnectivityService");
4180 }
4181
The Android Open Source Project28527d22009-03-03 19:31:44 -08004182 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07004183 mContext.enforceCallingOrSelfPermission(
4184 android.Manifest.permission.ACCESS_NETWORK_STATE,
4185 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08004186 }
4187
Junyu Lai71b51532024-02-01 10:39:01 +08004188 @CheckResult
4189 private boolean hasAccessPermission(int pid, int uid) {
lucaslinc582d502022-01-27 09:07:00 +08004190 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
4191 == PERMISSION_GRANTED;
4192 }
4193
paulhua6ee2122021-02-22 15:40:43 +08004194 /**
4195 * Performs a strict and comprehensive check of whether a calling package is allowed to
4196 * change the state of network, as the condition differs for pre-M, M+, and
4197 * privileged/preinstalled apps. The caller is expected to have either the
4198 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
4199 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
4200 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
4201 * permission and cannot be revoked. See http://b/23597341
4202 *
4203 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
4204 * of this app will be updated to the current time.
4205 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07004206 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08004207 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
4208 == PackageManager.PERMISSION_GRANTED) {
4209 return;
4210 }
4211
4212 if (callingPkg == null) {
4213 throw new SecurityException("Calling package name is null.");
4214 }
4215
4216 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
4217 final int uid = mDeps.getCallingUid();
4218 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
4219 callingPkg, callingAttributionTag, null /* message */);
4220
4221 if (mode == AppOpsManager.MODE_ALLOWED) {
4222 return;
4223 }
4224
4225 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
4226 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
4227 return;
4228 }
4229
4230 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
4231 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
4232 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08004233 }
4234
Charles He9369e612017-05-15 17:07:18 +01004235 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08004236 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01004237 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09004238 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01004239 }
4240
Quang Luong98858d62023-02-11 00:25:24 +00004241 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004242 enforceAnyPermissionOf(mContext,
4243 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00004244 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004245 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4246 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
4247 }
4248
paulhu8e96a752019-08-12 16:25:11 +08004249 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09004250 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07004251 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08004252 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08004253 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08004254 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08004255 }
4256
Aaron Huangebbfd3c2020-04-14 13:43:49 +08004257 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09004258 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07004259 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08004260 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08004261 android.Manifest.permission.NETWORK_SETTINGS,
4262 android.Manifest.permission.NETWORK_FACTORY,
4263 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
4264 }
4265
4266 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09004267 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07004268 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08004269 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08004270 android.Manifest.permission.MANAGE_TEST_NETWORKS,
4271 android.Manifest.permission.NETWORK_FACTORY,
4272 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
4273 }
4274
Junyu Lai71b51532024-02-01 10:39:01 +08004275 @CheckResult
4276 private boolean hasNetworkFactoryOrSettingsPermission(int pid, int uid) {
lucaslin69e1aa92022-03-22 18:15:09 +08004277 return PERMISSION_GRANTED == mContext.checkPermission(
4278 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
4279 || PERMISSION_GRANTED == mContext.checkPermission(
4280 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
4281 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09004282 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07004283 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08004284 }
4285
Junyu Lai71b51532024-02-01 10:39:01 +08004286 @CheckResult
4287 private boolean hasSettingsPermission() {
4288 return hasAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09004289 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09004290 }
4291
Junyu Lai71b51532024-02-01 10:39:01 +08004292 @CheckResult
4293 private boolean hasSettingsPermission(int pid, int uid) {
Chalard Jean9a396cc2018-02-21 18:43:54 +09004294 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09004295 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
4296 || PERMISSION_GRANTED == mContext.checkPermission(
4297 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09004298 }
4299
paulhu8e96a752019-08-12 16:25:11 +08004300 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08004301 enforceNetworkStackPermissionOr(mContext,
4302 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08004303 }
4304
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09004305 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08004306 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09004307 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08004308 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00004309 }
4310
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01004311 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08004312 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01004313 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
4314 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08004315 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01004316 }
4317
James Mattis8378aec2021-01-26 14:05:36 -08004318 private void enforceOemNetworkPreferencesPermission() {
4319 mContext.enforceCallingOrSelfPermission(
4320 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
4321 "ConnectivityService");
4322 }
4323
James Mattisfa270db2021-05-31 17:11:10 -07004324 private void enforceManageTestNetworksPermission() {
4325 mContext.enforceCallingOrSelfPermission(
4326 android.Manifest.permission.MANAGE_TEST_NETWORKS,
4327 "ConnectivityService");
4328 }
4329
Junyu Lai71b51532024-02-01 10:39:01 +08004330 @CheckResult
4331 private boolean hasNetworkStackPermission() {
4332 return hasAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09004333 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07004334 }
4335
Junyu Lai71b51532024-02-01 10:39:01 +08004336 @CheckResult
4337 private boolean hasNetworkStackPermission(int pid, int uid) {
4338 return hasAnyPermissionOf(mContext, pid, uid, android.Manifest.permission.NETWORK_STACK,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004339 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
4340 }
4341
Junyu Lai71b51532024-02-01 10:39:01 +08004342 @CheckResult
4343 private boolean hasSystemBarServicePermission(int pid, int uid) {
4344 return hasAnyPermissionOf(mContext, pid, uid,
Quang Anh Luong28eefef2023-11-07 09:43:41 +09004345 android.Manifest.permission.STATUS_BAR_SERVICE);
4346 }
4347
Junyu Lai71b51532024-02-01 10:39:01 +08004348 @CheckResult
4349 private boolean hasNetworkSignalStrengthWakeupPermission(int pid, int uid) {
4350 return hasAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08004351 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09004352 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4353 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08004354 }
4355
Junyu Lai71b51532024-02-01 10:39:01 +08004356 @CheckResult
4357 private boolean hasConnectivityRestrictedNetworksPermission(int callingUid,
Paul Hu8fc2a552022-05-04 18:44:42 +08004358 boolean checkUidsAllowedList) {
Junyu Lai71b51532024-02-01 10:39:01 +08004359 if (hasAnyPermissionOf(mContext,
Paul Hu8fc2a552022-05-04 18:44:42 +08004360 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
4361 return true;
4362 }
4363
4364 // fallback to ConnectivityInternalPermission
4365 // TODO: Remove this fallback check after all apps have declared
4366 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
Junyu Lai71b51532024-02-01 10:39:01 +08004367 if (hasAnyPermissionOf(mContext, android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08004368 return true;
4369 }
4370
4371 // Check whether uid is in allowed on restricted networks list.
4372 if (checkUidsAllowedList
4373 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
4374 return true;
4375 }
4376 return false;
4377 }
4378
4379 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
4380 final int callingUid = mDeps.getCallingUid();
Junyu Lai71b51532024-02-01 10:39:01 +08004381 if (!hasConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08004382 throw new SecurityException("ConnectivityService: user " + callingUid
4383 + " has no permission to access restricted network.");
4384 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09004385 }
4386
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004387 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00004388 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004389 }
4390
Junyu Lai71b51532024-02-01 10:39:01 +08004391 @CheckResult
4392 private boolean hasLocalMacAddressPermission(int pid, int uid) {
Roshan Pius98f59ec2021-02-23 08:47:39 -08004393 return PERMISSION_GRANTED == mContext.checkPermission(
4394 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
4395 }
4396
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09004397 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07004398 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07004399 }
4400
4401 private void sendInetConditionBroadcast(NetworkInfo info) {
4402 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
4403 }
4404
Wink Saville4f0de1e2011-08-04 15:01:58 -07004405 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07004406 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07004407 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07004408 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08004409 if (info.isFailover()) {
4410 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4411 info.setFailover(false);
4412 }
4413 if (info.getReason() != null) {
4414 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4415 }
4416 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07004417 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
4418 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08004419 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07004420 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07004421 return intent;
4422 }
4423
4424 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
4425 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
4426 }
4427
Michael Groover73f69482023-01-27 11:01:25 -06004428 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
4429 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08004430 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
4431 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04004432 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09004433 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09004434 if (!mSystemReady
4435 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08004436 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04004437 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08004438 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004439 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07004440 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07004441 }
4442
Dianne Hackborn66dd0332015-12-09 17:22:26 -08004443 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07004444 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08004445 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07004446 final NetworkInfo ni = intent.getParcelableExtra(
4447 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08004448 final BroadcastOptions opts = BroadcastOptions.makeBasic();
4449 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08004450 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08004451 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08004452 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08004453 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07004454 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00004455 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07004456 } finally {
4457 Binder.restoreCallingIdentity(ident);
4458 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04004459 }
4460 }
4461
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08004462 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
4463 NetworkInfo info) {
4464 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09004465 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08004466
4467 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
4468 try {
4469 // This allows us to discard older broadcasts still waiting to be delivered
4470 // which have the same namespace and key.
4471 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
4472 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
4473 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07004474 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08004475 } catch (UnsupportedApiLevelException e) {
4476 Log.wtf(TAG, "Using unsupported API" + e);
4477 }
4478 }
4479
4480 @VisibleForTesting
4481 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
4482 final StringBuilder sb = new StringBuilder();
4483 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
4484 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
4485 sb.append(info.getExtraInfo());
4486 return sb.toString();
4487 }
4488
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09004489 /**
Aaron Huang96011892020-06-27 07:18:23 +08004490 * Called by SystemServer through ConnectivityManager when the system is ready.
4491 */
4492 @Override
4493 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004494 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08004495 throw new SecurityException("Calling Uid is not system uid.");
4496 }
4497 systemReadyInternal();
4498 }
4499
4500 /**
4501 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09004502 */
4503 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08004504 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004505 // Load flags after PackageManager is ready to query module version
4506 mFlags.loadFlags(mDeps, mContext);
4507
Aaron Huang9a57acf2020-12-08 10:03:29 +08004508 // Since mApps in PermissionMonitor needs to be populated first to ensure that
4509 // listening network request which is sent by MultipathPolicyTracker won't be added
4510 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
4511 // be called after PermissionMonitor#startMonitoring().
4512 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
4513 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
4514 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00004515 final ConditionVariable startMonitoringDone = new ConditionVariable();
4516 mHandler.post(() -> {
4517 mPermissionMonitor.startMonitoring();
4518 startMonitoringDone.open();
4519 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09004520 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08004521 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004522
Hugo Benichie5220992017-04-26 14:53:28 +09004523 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04004524 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08004525 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07004526 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08004527 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04004528 }
4529 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07004530
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07004531 // Create network requests for always-on networks.
4532 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00004533
4534 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09004535 // Note that updating can be skipped here if the list is empty only because no uid
4536 // rules are applied before system ready. Normally, the empty uid list means to clear
4537 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00004538 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
4539 updateMobileDataPreferredUids();
4540 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09004541
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00004542 if (mSatelliteAccessController != null) {
4543 mSatelliteAccessController.start();
4544 }
4545
Motomu Utsumi4fcaa4e2024-02-28 17:15:41 +09004546 if (mCarrierPrivilegeAuthenticator != null) {
4547 mCarrierPrivilegeAuthenticator.start();
4548 }
4549
Patrick Rohr611ce3f2025-01-10 14:20:27 -08004550 if (mL2capNetworkProvider != null) {
4551 mL2capNetworkProvider.start();
4552 }
4553
Motomu Utsumi166f9662022-09-01 10:35:29 +09004554 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09004555 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09004556 mBpfNetMaps.setPullAtomCallback(mContext);
4557 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09004558 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
4559 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00004560 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
4561 // have permission problem. While CV#block() is unbounded in time and can in principle block
4562 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
4563 // could have blocked forever too.
4564 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08004565 }
4566
The Android Open Source Project28527d22009-03-03 19:31:44 -08004567 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08004568 * Start listening for default data network activity state changes.
4569 */
4570 @Override
4571 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08004572 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08004573 }
4574
4575 /**
4576 * Stop listening for default data network activity state changes.
4577 */
4578 @Override
4579 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08004580 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08004581 }
4582
4583 /**
4584 * Check whether the default network radio is currently active.
4585 */
4586 @Override
4587 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08004588 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08004589 }
4590
4591 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09004592 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09004593 * and set it on it's iface.
4594 */
Junyu Lai970963e2022-10-25 15:46:47 +08004595 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004596 final String iface = newLp.getInterfaceName();
4597 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00004598 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09004599 // Silently ignore unset MTU value.
4600 return;
4601 }
Hansen Kurli04252032022-12-07 11:21:49 +00004602 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
4603 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
4604 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004605 return;
4606 }
Hansen Kurli04252032022-12-07 11:21:49 +00004607 // Cannot set MTU without interface name
4608 if (TextUtils.isEmpty(iface)) {
4609 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004610 return;
4611 }
sy.yun4aa73922013-09-02 05:24:09 +09004612
Hansen Kurli04252032022-12-07 11:21:49 +00004613 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
4614 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07004615 return;
4616 }
4617
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004618 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004619 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08004620 mNetd.interfaceSetMtu(iface, mtu);
4621 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08004622 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004623 }
4624 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07004625
Chenbo Feng15416292018-11-08 17:36:21 -08004626 @VisibleForTesting
4627 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04004628
Junyu Lai970963e2022-10-25 15:46:47 +08004629 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07004630 String[] values = null;
4631 if (tcpBufferSizes != null) {
4632 values = tcpBufferSizes.split(",");
4633 }
4634
4635 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07004636 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07004637 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
4638 values = tcpBufferSizes.split(",");
4639 }
4640
4641 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
4642
4643 try {
Aaron Huang6616df32020-10-30 22:04:25 +08004644 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07004645
Chenbo Feng15416292018-11-08 17:36:21 -08004646 String rmemValues = String.join(" ", values[0], values[1], values[2]);
4647 String wmemValues = String.join(" ", values[3], values[4], values[5]);
4648 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07004649 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08004650 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07004651 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07004652 }
4653 }
4654
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07004655 @Override
4656 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09004657 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07004658 NETWORK_RESTORE_DELAY_PROP_NAME);
4659 if(restoreDefaultNetworkDelayStr != null &&
4660 restoreDefaultNetworkDelayStr.length() != 0) {
4661 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01004662 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07004663 } catch (NumberFormatException e) {
4664 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004665 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07004666 // if the system property isn't set, use the value for the apn type
4667 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
4668
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09004669 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
4670 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07004671 }
4672 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08004673 }
4674
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004675 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09004676 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004677 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09004678 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08004679 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004680 // Start gathering diagnostic information.
4681 netDiags.add(new NetworkDiagnostics(
4682 nai.network,
4683 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08004684 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004685 DIAG_TIME_MS));
4686 }
4687
4688 for (NetworkDiagnostics netDiag : netDiags) {
4689 pw.println();
4690 netDiag.waitForMeasurements();
4691 netDiag.dump(pw);
4692 }
4693 }
4694
The Android Open Source Project28527d22009-03-03 19:31:44 -08004695 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004696 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
4697 @Nullable String[] args) {
Junyu Lai71b51532024-02-01 10:39:01 +08004698 if (!hasDumpPermission(mContext, TAG, writer)) return;
Chiachang Wanga101f852021-04-19 10:59:24 +08004699
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08004700 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07004701 }
4702
Junyu Lai71b51532024-02-01 10:39:01 +08004703 @CheckResult
4704 private boolean hasDumpPermission(Context context, String tag, PrintWriter pw) {
lucaslin99473f62020-12-10 15:10:54 +08004705 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4706 != PackageManager.PERMISSION_GRANTED) {
4707 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004708 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08004709 + " due to missing android.permission.DUMP permission");
4710 return false;
4711 } else {
4712 return true;
4713 }
4714 }
4715
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08004716 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004717 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004718
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004719 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004720 dumpNetworkDiagnostics(pw);
4721 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004722 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004723 dumpNetworks(pw);
4724 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004725 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004726 dumpNetworkRequests(pw);
4727 return;
Ken Chene6d511f2022-01-25 11:10:42 +08004728 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
4729 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
4730 dumpTrafficController(pw, fd, verbose);
4731 return;
KH Shi855712a2023-06-21 17:15:35 +08004732 } else if (CollectionUtils.contains(args, CLATEGRESS4RAWBPFMAP_ARG)) {
4733 dumpClatBpfRawMap(pw, true /* isEgress4Map */);
4734 return;
4735 } else if (CollectionUtils.contains(args, CLATINGRESS6RAWBPFMAP_ARG)) {
4736 dumpClatBpfRawMap(pw, false /* isEgress4Map */);
4737 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004738 }
Erik Kline9647f382015-06-05 17:47:34 +09004739
Junyu Lai0da479b2022-04-20 15:06:29 +08004740 pw.println("NetworkProviders for:");
4741 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004742 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08004743 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004744 }
Junyu Lai0da479b2022-04-20 15:06:29 +08004745 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004746 pw.println();
4747
Chalard Jean5b409c72021-02-04 13:12:59 +09004748 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004749 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09004750 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004751 pw.println("none");
4752 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09004753 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08004754 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08004755 pw.println();
4756
James Mattis8b298a02021-06-01 22:34:04 -07004757 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08004758 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07004759 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08004760 pw.decreaseIndent();
4761 pw.println();
4762
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004763 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004764 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004765 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004766 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004767 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08004768
junyulaif2c67e42018-08-07 19:50:45 +08004769 pw.println("Status for known UIDs:");
4770 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00004771 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08004772 for (int i = 0; i < size; i++) {
4773 // Don't crash if the array is modified while dumping in bugreports.
4774 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00004775 final int uid = mUidBlockedReasons.keyAt(i);
4776 final int blockedReasons = mUidBlockedReasons.valueAt(i);
4777 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00004778 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08004779 } catch (ArrayIndexOutOfBoundsException e) {
4780 pw.println(" ArrayIndexOutOfBoundsException");
4781 } catch (ConcurrentModificationException e) {
4782 pw.println(" ConcurrentModificationException");
4783 }
4784 }
4785 pw.println();
4786 pw.decreaseIndent();
4787
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004788 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004789 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004790 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004791 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004792 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004793
Junyu Lai0da479b2022-04-20 15:06:29 +08004794 pw.println("Network Offers:");
4795 pw.increaseIndent();
4796 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
4797 pw.println(offerInfo.offer);
4798 }
4799 pw.decreaseIndent();
4800 pw.println();
4801
Robert Greenwalt94e22142014-07-30 16:31:24 -07004802 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07004803
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004804 pw.println();
markchien5e866652019-09-30 14:40:57 +08004805 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07004806
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004807 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004808 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004809
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004810 pw.println();
Motomu Utsumi8fad95c2024-04-15 19:07:55 +09004811 dumpDestroySockets(pw);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004812
Maciej Żenczykowskif0da1be2024-06-16 05:02:50 -07004813 if (mDeps.isAtLeastT()) {
4814 // R: https://android.googlesource.com/platform/system/core/+/refs/heads/android11-release/rootdir/init.rc
4815 // shows /dev/cg2_bpf
4816 // S: https://android.googlesource.com/platform/system/core/+/refs/heads/android12-release/rootdir/init.rc
4817 // does not
4818 // Thus cgroups are mounted at /dev/cg2_bpf on R and not on /sys/fs/cgroup
4819 // so the following won't work (on R) anyway.
4820 // The /sys/fs/cgroup path is only actually enforced/required starting with U,
4821 // but it is very likely to already be the case (though not guaranteed) on T.
4822 // I'm not at all sure about S - let's just skip it to get rid of lint warnings.
4823 pw.println();
4824 dumpBpfProgramStatus(pw);
4825 }
Junyu Lai155760b2023-10-05 14:51:00 +08004826
Chalard Jean53017782022-11-24 17:13:44 +09004827 if (null != mCarrierPrivilegeAuthenticator) {
4828 pw.println();
4829 mCarrierPrivilegeAuthenticator.dump(pw);
4830 }
4831
Junyu Lai155760b2023-10-05 14:51:00 +08004832 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004833
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004834 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004835 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09004836 pw.println("mNetworkRequestInfoLogs (most recent first):");
4837 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004838 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09004839 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09004840
4841 pw.println();
4842 pw.println("mNetworkInfoBlockingLogs (most recent first):");
4843 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004844 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09004845 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09004846
4847 pw.println();
4848 pw.println("NetTransition WakeLock activity (most recent first):");
4849 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004850 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
4851 pw.println("total releases: " + mTotalWakelockReleases);
4852 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
4853 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
4854 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4855 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4856 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4857 }
James Mattiscb1e0362021-04-06 17:07:42 -07004858 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004859
4860 pw.println();
4861 pw.println("bandwidth update requests (by uid):");
4862 pw.increaseIndent();
4863 synchronized (mBandwidthRequests) {
4864 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4865 pw.println("[" + mBandwidthRequests.keyAt(i)
4866 + "]: " + mBandwidthRequests.valueAt(i));
4867 }
4868 }
4869 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004870 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004871
James Mattiscb1e0362021-04-06 17:07:42 -07004872 pw.println();
4873 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4874 pw.increaseIndent();
4875 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004876 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004877 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004878
4879 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004880
4881 pw.println();
4882 pw.println("Permission Monitor:");
4883 pw.increaseIndent();
4884 mPermissionMonitor.dump(pw);
4885 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004886
4887 pw.println();
4888 pw.println("Legacy network activity:");
4889 pw.increaseIndent();
4890 mNetworkActivityTracker.dump(pw);
4891 pw.decreaseIndent();
Yang Sunca537d52024-01-19 12:53:50 +08004892
4893 pw.println();
4894 pw.println("Multicast routing supported: " +
4895 (mMulticastRoutingCoordinatorService != null));
Suprabh Shukla724d8972024-03-26 16:59:11 -07004896 pw.println("Background firewall chain enabled: " + mBackgroundFirewallChainEnabled);
Motomu Utsumi727dd5d2024-08-27 19:59:48 +09004897 pw.println("IngressToVpnAddressFiltering: " + mIngressToVpnAddressFiltering);
The Android Open Source Project28527d22009-03-03 19:31:44 -08004898 }
4899
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004900 private void dumpNetworks(IndentingPrintWriter pw) {
4901 for (NetworkAgentInfo nai : networksSortedById()) {
4902 pw.println(nai.toString());
4903 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004904 pw.println("Nat464Xlat:");
4905 pw.increaseIndent();
4906 nai.dumpNat464Xlat(pw);
4907 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004908 pw.println(String.format(
4909 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4910 nai.numForegroundNetworkRequests(),
4911 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4912 nai.numBackgroundNetworkRequests(),
4913 nai.numNetworkRequests()));
4914 pw.increaseIndent();
4915 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4916 pw.println(nai.requestAt(i).toString());
4917 }
4918 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004919 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004920 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004921 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004922 pw.decreaseIndent();
4923 pw.decreaseIndent();
4924 }
4925 }
4926
James Mattis8b298a02021-06-01 22:34:04 -07004927 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4928 if (!mProfileNetworkPreferences.isEmpty()) {
4929 pw.println("Profile preferences:");
4930 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004931 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004932 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004933 }
James Mattis8b298a02021-06-01 22:34:04 -07004934 if (!mOemNetworkPreferences.isEmpty()) {
4935 pw.println("OEM preferences:");
4936 pw.increaseIndent();
4937 pw.println(mOemNetworkPreferences);
4938 pw.decreaseIndent();
4939 }
4940 if (!mMobileDataPreferredUids.isEmpty()) {
4941 pw.println("Mobile data preferred UIDs:");
4942 pw.increaseIndent();
4943 pw.println(mMobileDataPreferredUids);
4944 pw.decreaseIndent();
4945 }
James Mattis45d81842021-01-10 14:24:24 -08004946
James Mattis8b298a02021-06-01 22:34:04 -07004947 pw.println("Default requests:");
4948 pw.increaseIndent();
4949 dumpPerAppDefaultRequests(pw);
4950 pw.decreaseIndent();
4951 }
4952
4953 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004954 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4955 if (mDefaultRequest == defaultRequest) {
4956 continue;
4957 }
4958
James Mattis8b298a02021-06-01 22:34:04 -07004959 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4960 final String networkOutput;
4961 if (null == satisfier) {
4962 networkOutput = "null";
4963 } else if (mNoServiceNetwork.equals(satisfier)) {
4964 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004965 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004966 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004967 }
James Mattis8b298a02021-06-01 22:34:04 -07004968 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4969 ? "" : " asUid: " + defaultRequest.mAsUid;
4970 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4971 + defaultRequest.mPid + asUidString + "]";
4972 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4973 + " Preference order: " + defaultRequest.mPreferenceOrder
4974 + " Tracked UIDs: " + defaultRequest.getUids();
4975 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004976 }
4977 }
4978
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004979 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004980 NetworkRequestInfo[] infos = null;
4981 while (infos == null) {
4982 try {
4983 infos = requestsSortedById();
4984 } catch (ConcurrentModificationException e) {
4985 // mNetworkRequests should only be accessed from handler thread, except dump().
4986 // As dump() is never called in normal usage, it would be needlessly expensive
4987 // to lock the collection only for its benefit. Instead, retry getting the
4988 // requests if ConcurrentModificationException is thrown during dump().
4989 }
4990 }
4991 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004992 pw.println(nri.toString());
4993 }
4994 }
4995
Ken Chene6d511f2022-01-25 11:10:42 +08004996 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4997 boolean verbose) {
4998 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004999 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08005000 } catch (ServiceSpecificException e) {
5001 pw.println(e.getMessage());
5002 } catch (IOException e) {
5003 loge("Dump BPF maps failed, " + e);
5004 }
5005 }
5006
KH Shi855712a2023-06-21 17:15:35 +08005007 private void dumpClatBpfRawMap(IndentingPrintWriter pw, boolean isEgress4Map) {
5008 for (NetworkAgentInfo nai : networksSortedById()) {
5009 if (nai.clatd != null) {
5010 nai.clatd.dumpRawBpfMap(pw, isEgress4Map);
5011 break;
5012 }
5013 }
5014 }
5015
Chalard Jean524f0b12021-10-25 21:11:56 +09005016 private void dumpAllRequestInfoLogsToLogcat() {
5017 try (PrintWriter logPw = new PrintWriter(new Writer() {
5018 @Override
5019 public void write(final char[] cbuf, final int off, final int len) {
5020 // This method is called with 0-length and 1-length arrays for empty strings
5021 // or strings containing only the DEL character.
5022 if (len <= 1) return;
5023 Log.e(TAG, new String(cbuf, off, len));
5024 }
5025 @Override public void flush() {}
5026 @Override public void close() {}
5027 })) {
5028 mNetworkRequestInfoLogs.dump(logPw);
5029 }
5030 }
5031
Hugo Benichia480ba52018-09-03 08:19:02 +09005032 /**
5033 * Return an array of all current NetworkAgentInfos sorted by network id.
5034 */
5035 private NetworkAgentInfo[] networksSortedById() {
5036 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005037 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08005038 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09005039 return networks;
5040 }
5041
5042 /**
5043 * Return an array of all current NetworkRequest sorted by request id.
5044 */
James Mattis258ea3c2020-11-15 15:04:40 -08005045 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08005046 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09005047 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08005048 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08005049 // Sort the array based off the NRI containing the min requestId in its requests.
5050 Arrays.sort(requests,
5051 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
5052 Comparator.comparingInt(req -> req.requestId)).requestId
5053 )
5054 );
Hugo Benichia480ba52018-09-03 08:19:02 +09005055 return requests;
5056 }
5057
Lorenzo Colittib54bea92016-04-05 17:52:16 +09005058 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08005059 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07005060 if (officialNai != null && officialNai.equals(nai)) return true;
5061 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09005062 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07005063 " - " + nai);
5064 }
5065 return false;
5066 }
5067
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005068 private boolean isDisconnectRequest(Message msg) {
5069 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
5070 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
5071 return info.getState() == NetworkInfo.State.DISCONNECTED;
5072 }
5073
Robert Greenwalt2034b912009-08-12 16:08:25 -07005074 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005075 private class NetworkStateTrackerHandler extends Handler {
5076 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07005077 super(looper);
5078 }
5079
Lorenzo Colittib54bea92016-04-05 17:52:16 +09005080 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005081 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
5082 final NetworkAgentInfo nai = arg.first;
Chalard Jean34ccc712025-03-10 15:35:31 +09005083
Pechetty Sravani (xWF)a5ec9b42025-03-17 00:48:05 -07005084 // If the network has been destroyed, the only thing that it can do is disconnect.
5085 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Chalard Jeanc2cf5ea2025-03-17 14:36:03 +09005086 if (DBG) {
5087 log("Message " + eventName(msg.what) + " from destroyed agent with netId "
5088 + nai.network.netId);
5089 }
Pechetty Sravani (xWF)a5ec9b42025-03-17 00:48:05 -07005090 return;
5091 }
5092
Chalard Jean3c040002025-03-18 09:28:41 +09005093 if (mQueueNetworkAgentEventsInSystemServer && nai.maybeEnqueueMessage(msg)) {
5094 // If the message is enqueued, the NAI will replay it immediately
5095 // when registration is complete. It does this by sending all the
5096 // messages in the order received immediately after the
5097 // EVENT_AGENT_REGISTERED message.
Chalard Jeanc2cf5ea2025-03-17 14:36:03 +09005098 if (DBG) {
5099 log("Message " + eventName(msg.what) + " enqueued for agent with netId "
5100 + nai.network.netId);
5101 }
Chalard Jean3c040002025-03-18 09:28:41 +09005102 return;
5103 }
5104
5105 // If the nai has been registered (and doesn't enqueue), it should now be
5106 // in the list of NAIs.
5107 if (!mNetworkAgentInfos.contains(nai)) {
5108 // TODO : this is supposed to be impossible
5109 if (VDBG) {
5110 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
5111 }
5112 return;
5113 }
5114
Lorenzo Colittib54bea92016-04-05 17:52:16 +09005115 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005116 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09005117 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
5118 if (!nai.respectsNcStructuralConstraints(proposed)) {
5119 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
5120 + nai.networkCapabilities + " -> " + proposed);
5121 disconnectAndDestroyNetwork(nai);
5122 return;
5123 }
5124 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09005125 final NetworkCapabilities sanitized =
5126 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09005127 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09005128 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005129 break;
5130 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005131 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005132 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09005133 processLinkPropertiesFromAgent(nai, newLp);
5134 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005135 break;
5136 }
5137 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005138 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005139 updateNetworkInfo(nai, info);
5140 break;
5141 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09005142 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
5143 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09005144 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09005145 break;
5146 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07005147 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09005148 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07005149 break;
5150 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07005151 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09005152 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09005153 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09005154 // Note that if the NAI had been connected, this would affect the
5155 // score, and therefore would require re-mixing the score and performing
5156 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04005157 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005158 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
5159 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08005160 // Mark the network as temporarily accepting partial connectivity so that it
5161 // will be validated (and possibly become default) even if it only provides
5162 // partial internet access. Note that if user connects to partial connectivity
5163 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
5164 // out of wifi coverage) and if the same wifi is available again, the device
5165 // will auto connect to this wifi even though the wifi has "no internet".
5166 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005167 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07005168 break;
5169 }
junyulai011b1f12019-01-03 18:50:15 +08005170 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005171 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005172 break;
5173 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005174 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005175 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09005176 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005177
5178 if (isLegacyLockdownNai(nai)
5179 && (underlying == null || underlying.size() != 1)) {
5180 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
5181 + " must have exactly one underlying network: " + underlying);
5182 }
5183
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005184 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
5185 nai.declaredUnderlyingNetworks = (underlying != null)
5186 ? underlying.toArray(new Network[0]) : null;
5187
5188 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
5189 if (DBG) {
5190 log(nai.toShortString() + " changed underlying networks to "
5191 + Arrays.toString(nai.declaredUnderlyingNetworks));
5192 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005193 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005194 notifyIfacesChangedForNetworkStats();
5195 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07005196 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005197 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005198 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
5199 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
5200 nai.teardownDelayMs = msg.arg1;
5201 } else {
5202 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
5203 }
Chalard Jean550b5212021-03-05 23:07:53 +09005204 break;
5205 }
5206 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
5207 nai.setLingerDuration((int) arg.second);
5208 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005209 }
Tyler Wear72388212021-09-09 14:49:02 -07005210 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
5211 DscpPolicy policy = (DscpPolicy) arg.second;
5212 if (mDscpPolicyTracker != null) {
5213 mDscpPolicyTracker.addDscpPolicy(nai, policy);
5214 }
5215 break;
5216 }
5217 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
5218 if (mDscpPolicyTracker != null) {
5219 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
5220 }
5221 break;
5222 }
5223 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
5224 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005225 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07005226 }
5227 break;
5228 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09005229 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005230 if (!nai.everConnected()) {
5231 Log.d(TAG, "unregisterAfterReplacement on never-connected "
5232 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09005233 teardownUnneededNetwork(nai);
5234 break;
5235 }
5236
5237 if (nai.isDestroyed()) {
5238 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
5239 + ", ignoring");
5240 break;
5241 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005242
5243 final int timeoutMs = (int) arg.second;
5244 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
5245 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
5246 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
5247 }
5248
5249 // Marking a network awaiting replacement is used to ensure that any requests
5250 // satisfied by the network do not switch to another network until a
5251 // replacement is available or the wait for a replacement times out.
5252 // If the network is inactive (i.e., nascent or lingering), then there are no
5253 // such requests, and there is no point keeping it. Just tear it down.
5254 // Note that setLingerDuration(0) cannot be used to do this because the network
5255 // could be nascent.
5256 nai.clearInactivityState();
5257 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5258 Log.d(TAG, nai.toShortString()
5259 + " marked awaiting replacement is unneeded, tearing down instead");
5260 teardownUnneededNetwork(nai);
5261 break;
5262 }
5263
5264 Log.d(TAG, "Marking " + nai.toShortString()
5265 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
5266 destroyNativeNetwork(nai);
5267
5268 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
5269 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
5270 // consider the fact that the network could already have disconnected or been
5271 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
5272 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
5273 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
5274 mKeepaliveTracker.handleStopAllKeepalives(nai,
5275 SocketKeepalive.ERROR_INVALID_NETWORK);
5276
5277 nai.updateScoreForNetworkAgentUpdate();
5278 // This rematch is almost certainly not going to result in any changes, because
5279 // the destroyed flag is only just above the "current satisfier wins"
5280 // tie-breaker. But technically anything that affects scoring should rematch.
5281 rematchAllNetworksAndRequests();
Chalard Jean9fdc9882025-03-21 10:13:47 +09005282 if (mQueueNetworkAgentEventsInSystemServer) {
5283 mHandler.postDelayed(() -> disconnectAndDestroyNetwork(nai), timeoutMs);
5284 } else {
5285 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
5286 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005287 break;
5288 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09005289 }
5290 }
5291
5292 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09005293 final int netId = msg.arg2;
5294 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005295 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09005296 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09005297 switch (msg.what) {
5298 default:
5299 return false;
lucasline117e2e2019-10-22 18:27:33 +08005300 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08005301 if (nai == null) {
5302 break;
5303 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09005304 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
5305 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08005306 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09005307 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08005308 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09005309 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08005310 if (probePrivateDnsCompleted) {
5311 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
5312 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005313 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08005314 }
5315 // Only show the notification when the private DNS is broken and the
5316 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005317 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08005318 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
5319 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005320 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08005321 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
5322 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
5323 // private DNS is broken, it means this network is being reevaluated.
5324 // Either probing private DNS is not necessary any more or it hasn't been
5325 // done yet. In either case, the networkCapabilities should be updated to
5326 // reflect the new status.
5327 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005328 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005329 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08005330 }
5331 break;
5332 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005333 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005334 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
5335
Erik Kline31b4a9e2018-01-11 21:07:29 +09005336 if (nai == null) break;
5337
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005338 handleNetworkTested(nai, results.mTestResult,
5339 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005340 break;
5341 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005342 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09005343 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07005344 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04005345 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08005346 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08005347 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08005348 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
5349 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04005350 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04005351 if (nai == null) {
5352 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
5353 break;
5354 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005355 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09005356 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005357 (PendingIntent) msg.obj,
5358 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07005359 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04005360 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04005361 break;
5362 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005363 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09005364 if (nai == null) break;
5365
Erik Kline9a62f012018-03-21 07:18:33 -07005366 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09005367 break;
5368 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09005369 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09005370 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08005371 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09005372 break;
5373 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005374 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09005375 return true;
5376 }
5377
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005378 private void handleNetworkTested(
5379 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09005380 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
5381 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09005382 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09005383
5384 // If there is any kind of working networking, then the NAI has been evaluated
5385 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
5386 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09005387 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09005388 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09005389 // Because of b/245893397, if the score is updated when updateCapabilities is called,
5390 // any callback that receives onAvailable for that rematch receives an extra caps
5391 // callback. To prevent that, update the score in the agent so the updates below won't
5392 // see an update to both caps and score at the same time.
5393 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09005394 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
5395
he_won.hwang881307a2022-03-15 21:23:52 +09005396 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
5397 // Assume the validation failure is due to a temporary failure after roaming
5398 // and ignore it. NetworkMonitor will continue to retry validation. If it
5399 // continues to fail after the block timeout expires, the network will be
5400 // marked unvalidated. If it succeeds, then validation state will not change.
5401 return;
5402 }
5403
Chalard Jean254bd162022-08-25 13:04:51 +09005404 final boolean wasValidated = nai.isValidated();
5405 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09005406 final boolean wasPortal = nai.captivePortalDetected();
5407 nai.setPartialConnectivity(partial);
5408 nai.setCaptivePortalDetected(portal);
5409 nai.updateScoreForNetworkAgentUpdate();
5410 final boolean partialConnectivityChanged = (wasPartial != partial);
5411 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005412
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005413 if (DBG) {
5414 final String logMsg = !TextUtils.isEmpty(redirectUrl)
5415 ? " with redirect to " + redirectUrl
5416 : "";
Remi NGUYEN VAN9da8b432023-11-10 18:12:37 +09005417 final String statusMsg;
5418 if (valid) {
5419 statusMsg = "passed";
5420 } else if (!TextUtils.isEmpty(redirectUrl)) {
5421 statusMsg = "detected a portal";
5422 } else {
5423 statusMsg = "failed";
5424 }
5425 log(nai.toShortString() + " validation " + statusMsg + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005426 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09005427 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09005428 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09005429 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005430 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005431 if (valid) {
5432 handleFreshlyValidatedNetwork(nai);
5433 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
5434 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005435 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005436 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08005437 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005438 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08005439 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005440 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08005441 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005442 NotificationType.PRIVATE_DNS_BROKEN);
5443 // If network becomes valid, the hasShownBroken should be reset for
5444 // that network so that the notification will be fired when the private
5445 // DNS is broken again.
5446 nai.networkAgentConfig.hasShownBroken = false;
5447 }
5448 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005449 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09005450 } else if (portalChanged) {
5451 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00005452 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09005453 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
5454 nai.onPreventAutomaticReconnect();
5455 teardownUnneededNetwork(nai);
5456 return;
5457 } else {
5458 updateCapabilitiesForNetwork(nai);
5459 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005460 } else if (becameEvaluated) {
5461 // If valid or partial connectivity changed, updateCapabilities* has
5462 // done the rematch.
5463 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005464 }
5465 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09005466
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005467 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005468 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005469 nai.onValidationStatusChanged(
5470 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
5471 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005472
5473 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09005474 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005475 // immediately. Re-notify partial connectivity silently if no internet
5476 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09005477 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005478 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09005479 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
5480 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005481 }
5482
Chalard Jean254bd162022-08-25 13:04:51 +09005483 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005484 handleNetworkUnvalidated(nai);
5485 }
5486 }
5487
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00005488 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
5489 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
5490 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
5491 // Do not avoid captive portal when network is wear proxy.
5492 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
5493 }
5494
Calvin Ondada1452016-10-11 15:10:46 -07005495 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08005496 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
5497 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07005498 }
5499
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005500 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
5501 switch (msg.what) {
5502 default:
5503 return false;
5504 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
5505 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
5506 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
5507 handleLingerComplete(nai);
5508 }
5509 break;
5510 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005511 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
5512 handleNetworkAgentRegistered(msg);
5513 break;
5514 }
5515 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
5516 handleNetworkAgentDisconnected(msg);
5517 break;
5518 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005519 }
5520 return true;
5521 }
5522
Lorenzo Colittib54bea92016-04-05 17:52:16 +09005523 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09005524 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08005525 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09005526 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09005527 maybeHandleNetworkAgentMessage(msg);
5528 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005529 }
5530 }
5531
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005532 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09005533 private final int mNetId;
5534 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005535
5536 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005537 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005538 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005539 }
5540
5541 @Override
5542 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
5543 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09005544 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005545 }
5546
5547 @Override
5548 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005549 // Legacy version of notifyNetworkTestedWithExtras.
5550 // Would only be called if the system has a NetworkStack module older than the
5551 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08005552 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005553 }
5554
5555 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005556 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09005557 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
5558 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005559 final Message msg = mTrackerHandler.obtainMessage(
5560 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09005561 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005562 new NetworkTestedResults(
5563 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005564 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005565
5566 // Invoke ConnectivityReport generation for this Network test event.
5567 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
5568 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005569
Cody Kestingf1120be2020-08-03 18:01:40 -07005570 // NetworkMonitor reports the network validation result as a bitmask while
5571 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
5572 // logical value for ConnectivityDiagnostics.
5573 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
5574 p.result);
5575
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005576 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07005577 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005578 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
5579 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
5580
Aaron Huang959d3642021-01-21 15:47:41 +08005581 ConnectivityReportEvent reportEvent =
5582 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
5583 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09005584 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005585 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005586 }
5587
5588 @Override
5589 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
5590 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
5591 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09005592 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005593 }
5594
5595 @Override
lucasline117e2e2019-10-22 18:27:33 +08005596 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
5597 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
5598 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09005599 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08005600 }
5601
5602 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09005603 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
5604 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
5605 EVENT_CAPPORT_DATA_CHANGED,
5606 0, mNetId, data));
5607 }
5608
5609 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09005610 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005611 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09005612 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005613
5614 final PendingIntent pendingIntent;
5615 // Only the system server can register notifications with package "android"
5616 final long token = Binder.clearCallingIdentity();
5617 try {
paulhu7746e4e2020-06-09 19:07:03 +08005618 pendingIntent = PendingIntent.getBroadcast(
5619 mContext,
5620 0 /* requestCode */,
5621 intent,
5622 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005623 } finally {
5624 Binder.restoreCallingIdentity(token);
5625 }
5626 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
5627 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09005628 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005629 }
5630
5631 @Override
5632 public void hideProvisioningNotification() {
5633 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09005634 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005635 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09005636
5637 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005638 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07005639 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08005640 }
5641
5642 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09005643 public int getInterfaceVersion() {
5644 return this.VERSION;
5645 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09005646
5647 @Override
5648 public String getInterfaceHash() {
5649 return this.HASH;
5650 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005651 }
5652
Cody Kestingf1120be2020-08-03 18:01:40 -07005653 /**
5654 * Converts the given NetworkMonitor-specific validation result bitmask to a
5655 * ConnectivityDiagnostics-specific validation result int.
5656 */
5657 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
5658 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
5659 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
5660 }
5661 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
5662 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
5663 }
5664 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
5665 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
5666 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
5667 }
5668
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07005669 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07005670 log("Data stall detected with methods: " + p.detectionMethod);
5671
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07005672 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07005673 int detectionMethod = 0;
5674 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
5675 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
5676 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
5677 }
5678 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
5679 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
5680 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
5681 p.tcpMetricsCollectionPeriodMillis);
5682 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07005683 }
5684
Cody Kestingf53a0752020-04-15 12:33:28 -07005685 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07005686 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08005687 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07005688
5689 // NetworkStateTrackerHandler currently doesn't take any actions based on data
5690 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
5691 // the cost of going through two handlers.
5692 mConnectivityDiagnosticsHandler.sendMessage(msg);
5693 }
5694
Cody Kestingb37958e2020-05-15 10:36:01 -07005695 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
5696 return (p.detectionMethod & detectionMethod) != 0;
5697 }
5698
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09005699 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
5700 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07005701 }
5702
Erik Klinea73af002018-06-26 18:53:43 +09005703 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
5704 if (nai == null) return;
5705 // If the Private DNS mode is opportunistic, reprogram the DNS servers
5706 // in order to restart a validation pass from within netd.
5707 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00005708 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005709 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09005710 }
5711 }
5712
Erik Kline31b4a9e2018-01-11 21:07:29 +09005713 private void handlePrivateDnsSettingsChanged() {
5714 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
5715
Chalard Jean2f52a0e2025-03-21 10:14:28 +09005716 forEachNetworkAgentInfo(nai -> {
Erik Kline9a62f012018-03-21 07:18:33 -07005717 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09005718 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05005719 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
5720 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +09005721 });
Erik Kline31b4a9e2018-01-11 21:07:29 +09005722 }
5723
Erik Kline9a62f012018-03-21 07:18:33 -07005724 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
5725 // Private DNS only ever applies to networks that might provide
5726 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09005727 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09005728
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005729 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07005730 // schedule DNS resolutions. If a DNS resolution is required the
5731 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005732 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07005733
5734 // With Private DNS bypass support, we can proceed to update the
5735 // Private DNS config immediately, even if we're in strict mode
5736 // and have not yet resolved the provider name into a set of IPs.
5737 updatePrivateDns(nai, cfg);
5738 }
5739
5740 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
5741 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08005742 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09005743 }
5744
dalyk1720e542018-03-05 12:42:22 -05005745 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
5746 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
5747 if (nai == null) {
5748 return;
5749 }
5750 mDnsManager.updatePrivateDnsValidation(update);
5751 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
5752 }
5753
paulhu7c0a2e62021-01-08 00:51:49 +08005754 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005755 int prefixLength) {
5756 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
5757 if (nai == null) return;
5758
paulhu7c0a2e62021-01-08 00:51:49 +08005759 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
5760 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005761
5762 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08005763 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005764 try {
paulhu7c0a2e62021-01-08 00:51:49 +08005765 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005766 prefixLength);
5767 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08005768 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005769 return;
5770 }
5771 }
5772
Lorenzo Colittid523d142020-04-01 20:16:30 +09005773 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005774 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
5775 }
5776
Hai Shalome58bdc62021-01-11 18:45:34 -08005777 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09005778 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08005779 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09005780 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
5781 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
5782 }
5783
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005784 /**
junyulai2b6f0c22021-02-03 20:15:30 +08005785 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005786 * @param nai the agent info to update
5787 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08005788 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005789 */
junyulai2b6f0c22021-02-03 20:15:30 +08005790 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
5791 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
5792 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005793 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08005794 // one lingered request, set inactive.
5795 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08005796 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08005797 if (DBG) log("Unsetting inactive " + nai.toShortString());
5798 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005799 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08005800 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005801 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08005802 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
5803 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005804 }
junyulai2b6f0c22021-02-03 20:15:30 +08005805 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005806 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005807 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005808 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005809 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05005810 }
5811
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005812 private void handleNetworkAgentRegistered(Message msg) {
5813 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
5814 if (!mNetworkAgentInfos.contains(nai)) {
5815 return;
5816 }
5817
5818 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
5819 if (VDBG) log("NetworkAgent registered");
5820 } else {
5821 loge("Error connecting NetworkAgent");
5822 mNetworkAgentInfos.remove(nai);
5823 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005824 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005825 synchronized (mNetworkForNetId) {
5826 mNetworkForNetId.remove(nai.network.getNetId());
Tommy Webba0dad0a2023-02-20 14:10:55 -05005827 mNetIdToAllowlist.remove(nai.network.getNetId());
5828 mNetIdToDisallowedUids.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005829 }
Tommy Webba0dad0a2023-02-20 14:10:55 -05005830 updateDisallowedUidsForNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005831 mNetIdManager.releaseNetId(nai.network.getNetId());
5832 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09005833 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005834 }
5835 }
5836 }
Paul Jensend5f53392014-11-25 15:26:53 -05005837
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005838 @VisibleForTesting
Chalard Jean324365a2025-03-21 10:12:38 +09005839 protected boolean shouldCreateNetworksImmediately(@NonNull NetworkCapabilities caps) {
Chalard Jeana16607f2023-06-27 19:16:00 +09005840 // The feature of creating the networks immediately was slated for U, but race conditions
5841 // detected late required this was flagged off.
Chalard Jean324365a2025-03-21 10:12:38 +09005842 // TODO : remove when it's determined that the code is stable
5843 return mQueueNetworkAgentEventsInSystemServer
5844 // Local network agents for Thread used to not create networks immediately,
5845 // but other local agents (tethering, P2P) require this to function.
5846 || (caps.hasCapability(NET_CAPABILITY_LOCAL_NETWORK)
5847 && !caps.hasTransport(TRANSPORT_THREAD));
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005848 }
5849
Chalard Jean324365a2025-03-21 10:12:38 +09005850 private boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005851 @NonNull NetworkInfo.State state) {
5852 if (nai.isCreated()) return false;
5853 if (state == NetworkInfo.State.CONNECTED) return true;
5854 if (state != NetworkInfo.State.CONNECTING) {
5855 // TODO: throw if no WTFs are observed in the field.
Junyu Lai91ef9d32025-02-26 17:33:27 +08005856 if (shouldCreateNetworksImmediately(nai.getCapsNoCopy())) {
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09005857 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
5858 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005859 return false;
5860 }
Junyu Lai91ef9d32025-02-26 17:33:27 +08005861 return nai.isVPN() || shouldCreateNetworksImmediately(nai.getCapsNoCopy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005862 }
5863
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005864 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09005865 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005866 }
5867
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005868 @VisibleForTesting
5869 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09005870 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09005871 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005872
5873 // If the network never roamed, return false. The check below is not sufficient if time
5874 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
5875 if (nai.lastRoamTime == 0) return false;
5876
he_won.hwang881307a2022-03-15 21:23:52 +09005877 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
5878 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005879 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09005880 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09005881 final long currentTimeMs = SystemClock.elapsedRealtime();
5882 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09005883 if (timeSinceLastRoam <= blockTimeOut) {
5884 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
5885 return true;
5886 }
5887 }
5888 return false;
5889 }
5890
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005891 private void handleNetworkAgentDisconnected(Message msg) {
5892 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07005893 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005894 }
5895
Chalard Jeand9fffc32018-05-11 20:19:20 +09005896 // Destroys a network, remove references to it from the internal state managed by
5897 // ConnectivityService, free its interfaces and clean up.
5898 // Must be called on the Handler thread.
5899 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005900 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07005901
5902 if (!mNetworkAgentInfos.contains(nai)) return;
5903
Chalard Jeand9fffc32018-05-11 20:19:20 +09005904 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09005905 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005906 }
Chalard Jean9fdc9882025-03-21 10:13:47 +09005907
5908 if (mQueueNetworkAgentEventsInSystemServer) {
5909 nai.disconnect();
5910 }
5911
lucaslinb25c9a62019-02-12 15:30:13 +08005912 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005913 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005914 // A network agent has disconnected.
5915 // TODO - if we move the logic to the network agent (have them disconnect
5916 // because they lost all their requests or because their score isn't good)
5917 // then they would disconnect organically, report their new state and then
5918 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08005919 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005920 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5921 null, null);
5922 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005923 final boolean wasDefault = isDefaultNetwork(nai);
5924 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005925 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005926 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005927 if (mTrackMultiNetworkActivities) {
5928 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5929 // the network becomes no longer the default network.
5930 mNetworkActivityTracker.removeDataActivityTracking(nai);
5931 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005932 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005933 // If this was a local network forwarded to some upstream, or if some local network was
5934 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005935 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005936 // If this is a local network with an upstream selector, remove the associated network
5937 // request.
5938 if (nai.isLocalNetwork()) {
5939 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5940 if (null != selector) {
5941 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5942 }
5943 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005944 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5945 // by other networks that are already connected. Perhaps that can be done by
5946 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5947 // of rematchAllNetworksAndRequests
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +09005948 notifyNetworkCallbacks(nai, CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005949 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005950
5951 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005952 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5953 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005954 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005955 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005956 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005957 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005958 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005959 synchronized (mNetworkForNetId) {
5960 // Remove the NetworkAgent, but don't mark the netId as
5961 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005962 mNetworkForNetId.remove(nai.network.getNetId());
Tommy Webba0dad0a2023-02-20 14:10:55 -05005963 mNetIdToAllowlist.remove(nai.network.getNetId());
5964 mNetIdToDisallowedUids.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005965 }
Tommy Webba0dad0a2023-02-20 14:10:55 -05005966 updateDisallowedUidsForNetwork(nai);
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005967 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005968 // Update allowed network lists in netd. This should be called after removing nai
5969 // from mNetworkAgentInfos.
5970 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005971 // Remove all previously satisfied requests.
5972 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005973 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005974 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005975 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005976 if (currentNetwork != null
5977 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005978 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005979 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5980 // rematch not to keep disconnected agents instead of setting it here ; this
5981 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005982 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005983 for (final NetworkOfferInfo noi : mNetworkOffers) {
5984 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005985 }
James Mattise3ef1912020-12-20 11:09:58 -08005986
Chalard Jean5b409c72021-02-04 13:12:59 +09005987 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005988 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumidff5df52024-05-14 18:19:43 +09005989 maybeDestroyPendingSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005990 ensureNetworkTransitionWakelock(nai.toShortString());
5991 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005992 }
5993 }
junyulai2b6f0c22021-02-03 20:15:30 +08005994 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005995 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005996 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005997 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005998 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005999 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09006000 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09006001
Aaron Huang9fe47be2021-06-08 13:11:45 +08006002 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
6003 // The obvious place to do this would be in makeDefault(), however makeDefault() is
6004 // not called by the rematch in this case. This is because the code above unset
6005 // this network from the default request's satisfier, and that is what the rematch
6006 // is using as its source data to know what the old satisfier was. So as far as the
6007 // rematch above is concerned, the old default network was null.
6008 // Therefore if there is no new default, the default network was null and is still
6009 // null, thus there was no change so makeDefault() is not called. So if the old
6010 // network had a proxy and there is no new default, the proxy tracker should be told
6011 // that there is no longer a default proxy.
6012 // Strictly speaking this is not essential because having a proxy setting when
6013 // there is no network is harmless, but it's still counter-intuitive so reset to null.
6014 mProxyTracker.setDefaultProxy(null);
6015 }
6016
Lorenzo Colittid5385c42021-03-11 01:32:09 +09006017 // Immediate teardown.
6018 if (nai.teardownDelayMs == 0) {
6019 destroyNetwork(nai);
6020 return;
6021 }
6022
6023 // Delayed teardown.
Xiaohui Niu339d6b22024-09-02 13:57:51 +08006024 if (nai.isCreated() && !nai.isDestroyed()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05306025 try {
6026 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
6027 } catch (RemoteException e) {
6028 Log.d(TAG, "Error marking network restricted during teardown: ", e);
6029 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09006030 }
6031 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
6032 }
6033
6034 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09006035 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09006036 // Tell netd to clean up the configuration for this network
6037 // (routing rules, DNS, etc).
6038 // This may be slow as it requires a lot of netd shelling out to ip and
6039 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09006040 // after we've rematched networks with requests (which might change the default
6041 // network or service a new request from an app), so network traffic isn't interrupted
6042 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08006043 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09006044 }
Chalard Jeandf29a852023-05-29 17:02:43 +09006045 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09006046 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
6047 // This can never run if the code above runs because shouldDestroyNativeNetwork is
6048 // false if the network was never created.
6049 // TODO: delete when S is no longer supported.
6050 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09006051 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08006052 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09006053 }
6054
Chalard Jean1e4c2182023-10-06 18:45:53 +09006055 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09006056 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09006057 // Step 1 : maybe this network was the upstream for one or more local networks.
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006058 forEachNetworkAgentInfo(local -> {
6059 if (!local.isLocalNetwork()) return; // return@forEach
Chalard Jean1e4c2182023-10-06 18:45:53 +09006060 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006061 if (null == selector) return; // return@forEach
Chalard Jean1e4c2182023-10-06 18:45:53 +09006062 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
6063 // null == nri can happen while disconnecting a network, because destroyNetwork() is
6064 // called after removing all associated NRIs from mNetworkRequests.
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006065 if (null == nri) return; // return@forEach
Chalard Jean1e4c2182023-10-06 18:45:53 +09006066 final NetworkAgentInfo satisfier = nri.getSatisfier();
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006067 if (disconnecting != satisfier) return; // return@forEach
Chalard Jean1e4c2182023-10-06 18:45:53 +09006068 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09006069 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
6070 // correctly contains null as an upstream.
6071 if (sendCallbacks) {
6072 nri.setSatisfier(null, null);
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +09006073 notifyNetworkCallbacks(local, CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean22350c92023-10-07 19:21:45 +09006074 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006075 });
Chalard Jean1e4c2182023-10-06 18:45:53 +09006076
6077 // Step 2 : maybe this is a local network that had an upstream.
6078 if (!disconnecting.isLocalNetwork()) return;
6079 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
6080 if (null == selector) return;
6081 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
6082 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
6083 // is called after removing all associated NRIs from mNetworkRequests.
6084 if (null == nri) return;
6085 final NetworkAgentInfo satisfier = nri.getSatisfier();
6086 if (null == satisfier) return;
6087 removeLocalNetworkUpstream(disconnecting, satisfier);
6088 }
6089
6090 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
6091 @NonNull final NetworkAgentInfo upstream) {
6092 try {
Yang Sun29037f62023-12-04 10:31:58 +08006093 final String localNetworkInterfaceName = localAgent.linkProperties.getInterfaceName();
6094 final String upstreamNetworkInterfaceName = upstream.linkProperties.getInterfaceName();
Chalard Jean1e4c2182023-10-06 18:45:53 +09006095 mRoutingCoordinatorService.removeInterfaceForward(
Yang Sun29037f62023-12-04 10:31:58 +08006096 localNetworkInterfaceName,
6097 upstreamNetworkInterfaceName);
6098 disableMulticastRouting(localNetworkInterfaceName, upstreamNetworkInterfaceName);
Chalard Jean1e4c2182023-10-06 18:45:53 +09006099 } catch (RemoteException e) {
6100 loge("Couldn't remove interface forward for "
6101 + localAgent.linkProperties.getInterfaceName() + " to "
6102 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
6103 }
6104 }
6105
Ken Chen6df7a902021-04-09 15:08:42 +08006106 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08006107 try {
6108 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08006109 final NativeNetworkConfig config;
6110 if (nai.isVPN()) {
6111 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08006112 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08006113 return false;
6114 }
6115 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
6116 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09006117 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08006118 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08006119 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09006120 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09006121 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
6122 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09006123 getNetworkPermission(nai.networkCapabilities),
6124 false /* secure */,
6125 VpnManager.TYPE_VPN_NONE,
6126 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08006127 }
Ken Chen6df7a902021-04-09 15:08:42 +08006128 mNetd.networkCreate(config);
6129 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08006130 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
6131 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08006132 return true;
6133 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08006134 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08006135 return false;
6136 }
6137 }
6138
Ken Chen6df7a902021-04-09 15:08:42 +08006139 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08006140 if (mDscpPolicyTracker != null) {
6141 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
6142 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09006143 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09006144 // the interface is going to go away. Don't send the callbacks however ; if the network
6145 // was is being disconnected the callbacks have already been sent, and if it is being
6146 // destroyed pending replacement they will be sent when it is disconnected.
6147 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Motomu Utsumib4772b12023-10-23 17:08:27 +09006148 updateIngressToVpnAddressFiltering(null, nai.linkProperties, nai);
Sarup Dalwani18b72622025-02-08 04:06:44 +00006149 updateLocalNetworkAddresses(null, nai.linkProperties);
Luke Huangfdd11f82019-04-09 18:41:49 +08006150 try {
Ken Chen6df7a902021-04-09 15:08:42 +08006151 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09006152 } catch (RemoteException | ServiceSpecificException e) {
6153 loge("Exception destroying network(networkDestroy): " + e);
6154 }
6155 try {
Ken Chen6df7a902021-04-09 15:08:42 +08006156 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08006157 } catch (RemoteException | ServiceSpecificException e) {
6158 loge("Exception destroying network: " + e);
6159 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09006160 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
6161 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
6162 // gets created, could add data to DnsManager data structures that will never get deleted.
6163 mDnsManager.removeNetwork(nai.network);
6164
6165 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09006166 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09006167 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
6168 }
6169
Chalard Jean254bd162022-08-25 13:04:51 +09006170 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09006171 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08006172 }
6173
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006174 // If this method proves to be too slow then we can maintain a separate
6175 // pendingIntent => NetworkRequestInfo map.
6176 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
6177 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006178 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
6179 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
6180 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09006181 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006182 return entry.getValue();
6183 }
6184 }
6185 return null;
6186 }
6187
Chalard Jean524f0b12021-10-25 21:11:56 +09006188 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09006189 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006190 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
6191 if (n.mBinder != null && n.mBinder == nri.mBinder) {
6192 // Temporary help to debug b/194394697 ; TODO : remove this function when the
6193 // bug is fixed.
6194 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09006195 throw new IllegalStateException("This NRI is already registered. New : " + nri
6196 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09006197 }
6198 }
6199 }
6200 }
6201
Chalard Jeanac9ace02022-01-26 16:54:05 +09006202 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
6203 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08006204 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09006205 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09006206 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006207 }
6208 return false;
6209 }
6210
Ying Xu0d06b942024-02-09 21:04:08 -08006211 private int getSubscriptionIdFromNetworkCaps(@NonNull final NetworkCapabilities caps) {
6212 if (mCarrierPrivilegeAuthenticator != null) {
6213 return mCarrierPrivilegeAuthenticator.getSubIdFromNetworkCapabilities(caps);
6214 }
6215 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
6216 }
6217
James Mattisf7027322020-12-13 16:28:14 -08006218 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006219 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08006220 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
6221 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
6222 final NetworkRequestInfo existingRequest =
6223 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006224 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08006225 if (DBG) {
6226 log("Replacing " + existingRequest.mRequests.get(0) + " with "
6227 + nri.mRequests.get(0) + " because their intents matched.");
6228 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006229 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08006230 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006231 }
Erik Kline05f2b402015-04-30 12:58:40 +09006232 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006233 }
6234
James Mattisf7027322020-12-13 16:28:14 -08006235 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006236 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08006237 }
6238
James Mattis3ce3d3c2021-02-09 18:18:28 -08006239 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006240 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08006241 for (final NetworkRequestInfo nri : nris) {
6242 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09006243 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08006244 for (final NetworkRequest req : nri.mRequests) {
6245 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08006246 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08006247 if (req.isListen()) {
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006248 forEachNetworkAgentInfo(network -> {
James Mattis45d81842021-01-10 14:24:24 -08006249 if (req.networkCapabilities.hasSignalStrength()
6250 && network.satisfiesImmutableCapabilitiesOf(req)) {
6251 updateSignalStrengthThresholds(network, "REGISTER", req);
6252 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006253 });
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00006254 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
6255 mNetworkRequestStateStatsMetrics.onNetworkRequestReceived(req);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006256 }
6257 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006258
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006259 // If this NRI has a satisfier already, it is replacing an older request that
6260 // has been removed. Track it.
6261 final NetworkRequest activeRequest = nri.getActiveRequest();
6262 if (null != activeRequest) {
6263 // If there is an active request, then for sure there is a satisfier.
6264 nri.getSatisfier().addRequest(activeRequest);
6265 }
Motomu Utsumid20727f2024-05-23 21:44:40 +09006266
6267 if (shouldTrackUidsForBlockedStatusCallbacks()
Motomu Utsumifa78c922025-02-06 16:24:29 +09006268 && nri.mMessenger != null
Motomu Utsumid20727f2024-05-23 21:44:40 +09006269 && !nri.mUidTrackedForBlockedStatus) {
6270 Log.wtf(TAG, "Registered nri is not tracked for sending blocked status: " + nri);
6271 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006272 }
James Mattisf7027322020-12-13 16:28:14 -08006273
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09006274 if (mFlags.noRematchAllRequestsOnRegister()) {
6275 rematchNetworksAndRequests(nris);
6276 } else {
6277 rematchAllNetworksAndRequests();
6278 }
James Mattis45d81842021-01-10 14:24:24 -08006279
Chalard Jean0354d8c2021-01-12 10:58:56 +09006280 // Requests that have not been matched to a network will not have been sent to the
6281 // providers, because the old satisfier and the new satisfier are the same (null in this
6282 // case). Send these requests to the providers.
6283 for (final NetworkRequestInfo nri : nris) {
6284 for (final NetworkOfferInfo noi : mNetworkOffers) {
6285 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08006286 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006287 }
6288 }
6289
James Mattisf7027322020-12-13 16:28:14 -08006290 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
6291 final int callingUid) {
6292 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006293 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08006294 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
6295 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
6296 handleReleaseNetworkRequest(
6297 nri.mRequests.get(0),
6298 callingUid,
6299 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006300 }
6301 }
6302
Lorenzo Colitti2666be82016-09-09 18:48:56 +09006303 // Determines whether the network is the best (or could become the best, if it validated), for
6304 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
6305 // on the value of reason:
6306 //
6307 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
6308 // then it should be torn down.
6309 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
6310 // then it should be lingered.
6311 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006312 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09006313
Chalard Jean254bd162022-08-25 13:04:51 +09006314 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09006315 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
6316 return false;
6317 }
6318
Lorenzo Colitti2666be82016-09-09 18:48:56 +09006319 final int numRequests;
6320 switch (reason) {
6321 case TEARDOWN:
6322 numRequests = nai.numRequestNetworkRequests();
6323 break;
6324 case LINGER:
6325 numRequests = nai.numForegroundNetworkRequests();
6326 break;
6327 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006328 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09006329 return true;
6330 }
6331
Chalard Jean947acd42021-03-08 22:29:27 +09006332 if (numRequests > 0) return false;
6333
Paul Jensende49eb12015-06-25 15:30:08 -04006334 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08006335 if (reason == UnneededFor.LINGER
6336 && !nri.isMultilayerRequest()
6337 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09006338 // Background requests don't affect lingering.
6339 continue;
6340 }
6341
James Mattis3d229892020-11-16 16:46:28 -08006342 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04006343 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05006344 }
6345 }
Paul Jensende49eb12015-06-25 15:30:08 -04006346 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05006347 }
6348
James Mattis3d229892020-11-16 16:46:28 -08006349 private boolean isNetworkPotentialSatisfier(
6350 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09006351 // While destroyed network sometimes satisfy requests (including occasionally newly
6352 // satisfying requests), *potential* satisfiers are networks that might beat a current
6353 // champion if they validate. As such, a destroyed network is never a potential satisfier,
6354 // because it's never a good idea to keep a destroyed network in case it validates.
6355 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
6356 // candidate after it's been replaced by another unvalidated network.
6357 if (candidate.isDestroyed()) return false;
6358 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08006359 // request, return immediately. For multilayer requests, check to see if any of the
6360 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08006361 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
6362 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08006363 return false;
6364 }
6365 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08006366 // This multilayer listen request is satisfied therefore no further requests need to be
6367 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08006368 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08006369 return false;
6370 }
James Mattis3d229892020-11-16 16:46:28 -08006371 // As non-multilayer listen requests have already returned, the below would only happen
6372 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08006373 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08006374 continue;
6375 }
Chalard Jean80685f42023-10-30 18:31:27 +09006376 // If there is hope for this network might validate and subsequently become the best
6377 // network for that request, then it is needed. Note that this network can't already
6378 // be the best for this request, or it would be the current satisfier, and therefore
6379 // there would be no need to call this method to find out if it is a *potential*
6380 // satisfier ("unneeded", the only caller, only calls this if this network currently
6381 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08006382 if (candidate.satisfies(req)) {
6383 // As soon as a network is found that satisfies a request, return. Specifically for
6384 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
6385 // is important so as to not evaluate lower priority requests further in
6386 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09006387 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
6388 ? nri.getSatisfier() : null;
6389 // Note that this catches two important cases:
6390 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
6391 // is currently satisfying the request. This is desirable when
6392 // cellular ends up validating but WiFi does not.
6393 // 2. Unvalidated WiFi will not be reaped when validated cellular
6394 // is currently satisfying the request. This is desirable when
6395 // WiFi ends up validating and out scoring cellular.
6396 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08006397 }
6398 }
6399
6400 return false;
6401 }
6402
Erik Kline0c04b742016-07-07 16:50:58 +09006403 private NetworkRequestInfo getNriForAppRequest(
6404 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006405 // Looking up the app passed param request in mRequests isn't possible since it may return
6406 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
6407 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08006408 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
6409 // to avoid potential race conditions when validating a package->uid mapping when sending
6410 // the callback on the very low-chance that an application shuts down prior to the callback
6411 // being sent.
6412 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
6413 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09006414
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006415 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08006416 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09006417 log(String.format("UID %d attempted to %s for unowned request %s",
6418 callingUid, requestedOperation, nri));
6419 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04006420 }
Erik Kline0c04b742016-07-07 16:50:58 +09006421 }
6422
6423 return nri;
6424 }
6425
James Mattisf7027322020-12-13 16:28:14 -08006426 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
6427 final String callingMethod) {
6428 if (nri.isMultilayerRequest()) {
6429 throw new IllegalStateException(
6430 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09006431 }
6432 }
6433
James Mattisf7027322020-12-13 16:28:14 -08006434 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09006435 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08006436 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
6437 // single NetworkRequest and thus does not apply to multilayer requests.
6438 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
6439 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09006440 return;
6441 }
James Mattis2516da32021-01-31 17:06:19 -08006442 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09006443 return;
6444 }
James Mattisf7027322020-12-13 16:28:14 -08006445 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
6446 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09006447 }
6448 handleRemoveNetworkRequest(nri);
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +09006449 callCallbackForRequest(nri, null, CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09006450 }
6451
James Mattisf7027322020-12-13 16:28:14 -08006452 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
6453 final int callingUid,
6454 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09006455 final NetworkRequestInfo nri =
6456 getNriForAppRequest(request, callingUid, "release NetworkRequest");
6457 if (nri == null) {
6458 return;
Erik Kline155a59a2015-11-25 12:49:38 +09006459 }
James Mattisf7027322020-12-13 16:28:14 -08006460 if (VDBG || (DBG && request.isRequest())) {
6461 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09006462 }
6463 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08006464 if (callOnUnavailable) {
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +09006465 callCallbackForRequest(nri, null, CALLBACK_UNAVAIL, 0);
Etan Cohenfbfdd842019-01-08 12:09:18 -08006466 }
Erik Kline155a59a2015-11-25 12:49:38 +09006467 }
Erik Kline0c04b742016-07-07 16:50:58 +09006468
James Mattisa076c532020-12-02 14:12:41 -08006469 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Motomu Utsumib16f75c2024-05-23 19:25:17 +09006470 handleRemoveNetworkRequest(nri, true /* untrackUids */);
6471 }
6472
6473 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri,
6474 final boolean untrackUids) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006475 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08006476 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07006477 if (null == mNetworkRequests.remove(req)) {
6478 logw("Attempted removal of untracked request " + req + " for nri " + nri);
6479 continue;
6480 }
James Mattisa076c532020-12-02 14:12:41 -08006481 if (req.isListen()) {
6482 removeListenRequestFromNetworks(req);
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00006483 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
6484 mNetworkRequestStateStatsMetrics.onNetworkRequestRemoved(req);
James Mattisa076c532020-12-02 14:12:41 -08006485 }
6486 }
James Mattis8f036802021-06-20 16:26:01 -07006487 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09006488 if (mDefaultNetworkRequests.remove(nri)) {
6489 // If this request was one of the defaults, then the UID rules need to be updated
6490 // WARNING : if the app(s) for which this network request is the default are doing
6491 // traffic, this will kill their connected sockets, even if an equivalent request
6492 // is going to be reinstated right away ; unconnected traffic will go on the default
6493 // until the new default is set, which will happen very soon.
6494 // TODO : The only way out of this is to diff old defaults and new defaults, and only
6495 // remove ranges for those requests that won't have a replacement
6496 final NetworkAgentInfo satisfier = nri.getSatisfier();
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +09006497 if (null != satisfier) {
Chalard Jean738c5bf2021-03-01 22:08:57 +09006498 try {
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +09006499 modifyNetworkUidRanges(false /* add */, satisfier, nri.getUids(),
6500 nri.getPreferenceOrderForNetd());
Chalard Jean738c5bf2021-03-01 22:08:57 +09006501 } catch (RemoteException e) {
6502 loge("Exception setting network preference default network", e);
6503 }
6504 }
6505 }
Junyu Lai35665cc2022-12-19 17:37:48 +08006506
Motomu Utsumib16f75c2024-05-23 19:25:17 +09006507 if (untrackUids) {
Motomu Utsumid20727f2024-05-23 21:44:40 +09006508 maybeUntrackUidAndClearBlockedReasons(nri);
Motomu Utsumib16f75c2024-05-23 19:25:17 +09006509 }
Erik Kline0c04b742016-07-07 16:50:58 +09006510 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09006511 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08006512
6513 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006514 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08006515 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08006516 }
6517 }
6518
Chalard Jean0354d8c2021-01-12 10:58:56 +09006519 // For all outstanding offers, cancel any of the layers of this NRI that used to be
6520 // needed for this offer.
6521 for (final NetworkOfferInfo noi : mNetworkOffers) {
6522 for (final NetworkRequest req : nri.mRequests) {
6523 if (req.isRequest() && noi.offer.neededFor(req)) {
6524 noi.offer.onNetworkUnneeded(req);
6525 }
6526 }
6527 }
James Mattisa076c532020-12-02 14:12:41 -08006528 }
6529
James Mattis3ce3d3c2021-02-09 18:18:28 -08006530 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Motomu Utsumib16f75c2024-05-23 19:25:17 +09006531 handleRemoveNetworkRequests(nris, true /* untrackUids */);
6532 }
6533
6534 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris,
6535 final boolean untrackUids) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006536 for (final NetworkRequestInfo nri : nris) {
6537 if (mDefaultRequest == nri) {
6538 // Make sure we never remove the default request.
6539 continue;
6540 }
Motomu Utsumib16f75c2024-05-23 19:25:17 +09006541 handleRemoveNetworkRequest(nri, untrackUids);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006542 }
6543 }
6544
James Mattisa076c532020-12-02 14:12:41 -08006545 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
6546 // listens don't have a singular affected Network. Check all networks to see
6547 // if this listen request applies and remove it.
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006548 forEachNetworkAgentInfo(nai -> {
James Mattisa076c532020-12-02 14:12:41 -08006549 nai.removeRequest(req.requestId);
6550 if (req.networkCapabilities.hasSignalStrength()
6551 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6552 updateSignalStrengthThresholds(nai, "RELEASE", req);
6553 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006554 });
James Mattisa076c532020-12-02 14:12:41 -08006555 }
6556
6557 /**
6558 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
6559 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
6560 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
6561 */
6562 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
6563 boolean wasKept = false;
6564 final NetworkAgentInfo nai = nri.getSatisfier();
6565 if (nai != null) {
6566 final int requestLegacyType = nri.getActiveRequest().legacyType;
6567 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
6568 nai.removeRequest(nri.getActiveRequest().requestId);
6569 if (VDBG || DDBG) {
6570 log(" Removing from current network " + nai.toShortString()
6571 + ", leaving " + nai.numNetworkRequests() + " requests.");
6572 }
6573 // If there are still lingered requests on this network, don't tear it down,
6574 // but resume lingering instead.
6575 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08006576 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08006577 notifyNetworkLosing(nai, now);
6578 }
6579 if (unneeded(nai, UnneededFor.TEARDOWN)) {
6580 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
6581 teardownUnneededNetwork(nai);
6582 } else {
6583 wasKept = true;
6584 }
James Mattisa076c532020-12-02 14:12:41 -08006585 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
6586 // Went from foreground to background.
6587 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09006588 }
6589
Erik Kline0c04b742016-07-07 16:50:58 +09006590 // Maintain the illusion. When this request arrived, we might have pretended
6591 // that a network connected to serve it, even though the network was already
6592 // connected. Now that this request has gone away, we might have to pretend
6593 // that the network disconnected. LegacyTypeTracker will generate that
6594 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08006595 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09006596 boolean doRemove = true;
6597 if (wasKept) {
6598 // check if any of the remaining requests for this network are for the
6599 // same legacy type - if so, don't remove the nai
6600 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6601 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08006602 if (otherRequest.legacyType == requestLegacyType
6603 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09006604 if (DBG) log(" still have other legacy request - leaving");
6605 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08006606 }
6607 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07006608 }
6609
Erik Kline0c04b742016-07-07 16:50:58 +09006610 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08006611 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09006612 }
6613 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006614 }
6615 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006616
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006617 /**
6618 * Perform the specified operation on all networks.
6619 *
6620 * This method will run |op| exactly once for each network currently registered at the
6621 * time it is called, even if |op| adds or removes networks.
6622 *
6623 * @param op the operation to perform. The operation is allowed to disconnect any number of
6624 * networks.
6625 */
6626 private void forEachNetworkAgentInfo(final Consumer<NetworkAgentInfo> op) {
6627 // Create a copy instead of iterating over the set so |op| is allowed to disconnect any
6628 // number of networks (which removes it from mNetworkAgentInfos). The copy is cheap
6629 // because there are at most a handful of NetworkAgents connected at any given time.
6630 final NetworkAgentInfo[] nais = new NetworkAgentInfo[mNetworkAgentInfos.size()];
6631 mNetworkAgentInfos.toArray(nais);
6632 for (NetworkAgentInfo nai : nais) {
6633 op.accept(nai);
6634 }
6635 }
6636
6637 /**
6638 * Check whether the specified condition is true for any network.
6639 *
6640 * This method will stop evaluating as soon as the condition returns true for any network.
6641 * The order of iteration is not contractual.
6642 *
6643 * @param condition the condition to verify. This method must not modify the set of networks in
6644 * any way.
6645 * @return whether {@code condition} returned true for any network
6646 */
6647 private boolean anyNetworkAgentInfo(final Predicate<NetworkAgentInfo> condition) {
6648 for (int i = mNetworkAgentInfos.size() - 1; i >= 0; i--) {
6649 if (condition.test(mNetworkAgentInfos.valueAt(i))) return true;
6650 }
6651 return false;
6652 }
6653
Junyu Lai00d92df2022-07-05 11:01:52 +08006654 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai71b51532024-02-01 10:39:01 +08006655 return hasAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09006656 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
6657 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
6658 }
6659
Lorenzo Colittid6459092016-07-04 12:55:44 +09006660 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006661 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08006662 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006663 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09006664 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006665 }
6666
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006667 @Override
lucaslin2240ef62019-03-12 13:08:03 +08006668 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
6669 enforceNetworkStackSettingsOrSetup();
6670 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
6671 encodeBool(accept), encodeBool(always), network));
6672 }
6673
6674 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006675 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08006676 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006677 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
6678 }
6679
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006680 @Override
6681 public void setTestAllowBadWifiUntil(long timeMs) {
6682 enforceSettingsPermission();
6683 if (!Build.isDebuggable()) {
6684 throw new IllegalStateException("Does not support in non-debuggable build");
6685 }
6686
6687 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
6688 throw new IllegalArgumentException("It should not exceed "
6689 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
6690 }
6691
6692 mHandler.sendMessage(
6693 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
6694 }
6695
chiachangwange0192a72023-02-06 13:25:01 +00006696 @Override
6697 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
6698 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00006699
6700 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
6701 throw new IllegalArgumentException("Argument should not exceed "
6702 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
6703 }
6704
6705 mHandler.sendMessage(
6706 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
6707 }
6708
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006709 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
6710 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
6711 " accept=" + accept + " always=" + always);
6712
6713 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6714 if (nai == null) {
6715 // Nothing to do.
6716 return;
6717 }
6718
Chalard Jean254bd162022-08-25 13:04:51 +09006719 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09006720 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006721 return;
6722 }
6723
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006724 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08006725 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006726 }
6727
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006728 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
6729 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08006730 // If network becomes partial connectivity and user already accepted to use this
6731 // network, we should respect the user's option and don't need to popup the
6732 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006733 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09006734 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09006735 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006736 }
6737
6738 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006739 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006740 }
6741
Lorenzo Colitti74baf412015-05-21 16:17:05 +09006742 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04006743 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006744 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09006745 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04006746 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09006747 }
6748
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006749 }
6750
lucaslin2240ef62019-03-12 13:08:03 +08006751 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
6752 boolean always) {
6753 if (DBG) {
6754 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
6755 + " always=" + always);
6756 }
6757
6758 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6759 if (nai == null) {
6760 // Nothing to do.
6761 return;
6762 }
6763
Chalard Jean254bd162022-08-25 13:04:51 +09006764 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08006765 // The network validated while the dialog box was up. Take no action.
6766 return;
6767 }
6768
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006769 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
6770 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08006771 }
6772
6773 // TODO: Use the current design or save the user choice into IpMemoryStore.
6774 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006775 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08006776 }
6777
6778 if (!accept) {
6779 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006780 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08006781 // Tear down the network.
6782 teardownUnneededNetwork(nai);
6783 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08006784 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
6785 // result in a partial connectivity result which will be processed by
6786 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08006787 //
6788 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
6789 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006790 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08006791 }
6792 }
6793
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006794 private void handleSetAvoidUnvalidated(Network network) {
6795 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09006796 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006797 // Nothing to do. The network either disconnected or revalidated.
6798 return;
6799 }
Chalard Jean254bd162022-08-25 13:04:51 +09006800 if (0L == nai.getAvoidUnvalidated()) {
6801 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09006802 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09006803 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006804 }
6805 }
6806
Chalard Jean5fb43c72022-09-08 19:03:14 +09006807 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09006808 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09006809 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09006810 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006811 }
6812
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09006813 @Override
6814 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08006815 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09006816 mHandler.post(() -> {
6817 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6818 if (nai == null) return;
6819 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006820 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09006821 });
6822 }
6823
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09006824 /**
6825 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
6826 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006827 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09006828 * @param appExtras Bundle to use as intent extras for the captive portal application.
6829 * Must be treated as opaque to avoid preventing the captive portal app to
6830 * update its arguments.
6831 */
6832 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006833 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08006834 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
6835 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09006836
6837 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
6838 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006839 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
6840 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09006841 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
6842
lucaslin75ff7022020-12-17 04:14:35 +08006843 final long token = Binder.clearCallingIdentity();
6844 try {
6845 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
6846 } finally {
6847 Binder.restoreCallingIdentity(token);
6848 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09006849 }
6850
Patrick Rohr7d6dfd52024-12-05 04:06:53 +00006851 public class CaptivePortalImpl extends ICaptivePortal.Stub implements IBinder.DeathRecipient {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006852 private final Network mNetwork;
Patrick Rohr7d6dfd52024-12-05 04:06:53 +00006853 // Binder object to track the lifetime of the setDelegateUid caller for cleanup purposes.
6854 //
6855 // Note that in theory it can happen that there are multiple callers for a given
6856 // object. For example, the app that receives the CaptivePortal object from the Intent
6857 // fired by startCaptivePortalAppInternal could send the object to another process, or
6858 // clone it. Only the first of these objects that calls setDelegateUid will properly
6859 // register a death recipient. Calls from the other objects will work, but only the
6860 // first object's death will cause the death recipient to fire.
6861 // TODO: track all callers by callerBinder instead of CaptivePortalImpl, store callerBinder
6862 // in a Set. When the death recipient fires, we can remove the callingBinder from the set,
6863 // and when the set is empty, we can clear the delegated UID.
6864 private IBinder mDelegateUidCaller;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006865
6866 private CaptivePortalImpl(Network network) {
6867 mNetwork = network;
6868 }
6869
6870 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006871 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006872 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
6873 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00006874 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
6875 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
6876 // Since the network will be disconnected, skip notifying NetworkMonitor
6877 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006878 }
6879
Chiachang Wang938bfba2020-01-09 13:50:55 +08006880 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006881 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006882 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006883 }
6884
6885 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08006886 public void appRequest(final int request) {
6887 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
6888 if (nm == null) return;
6889
6890 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wang73be9a02024-03-13 13:19:04 +00006891 // This enforceNetworkStackPermission() should be adopted to check
6892 // the required permission but this may be break OEM captive portal
6893 // apps. Simply ignore the request if the caller does not have
6894 // permission.
6895 if (!hasNetworkStackPermission()) {
6896 Log.e(TAG, "Calling appRequest() without proper permission. Skip");
6897 return;
6898 }
6899
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006900 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08006901 }
6902 }
6903
Patrick Rohr7d6dfd52024-12-05 04:06:53 +00006904 private int handleSetDelegateUid(int uid, @NonNull final IBinder callerBinder) {
6905 if (mDelegateUidCaller == null) {
6906 mDelegateUidCaller = callerBinder;
6907 try {
6908 // While technically unnecessary, it is safe to register a DeathRecipient for
6909 // a cleanup operation (where uid = INVALID_UID).
6910 mDelegateUidCaller.linkToDeath(this, 0);
6911 } catch (RemoteException e) {
6912 // remote has died, return early.
6913 return ENOTCONN;
6914 }
6915 }
6916
6917 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(mNetwork);
6918 if (nai == null) return ENOENT; // network does not exist anymore.
6919 if (nai.isDestroyed()) return ENOENT; // network has already been destroyed.
6920
6921 // TODO: consider allowing the uid to bypass VPN on all networks before V.
6922 if (!mDeps.isAtLeastV()) return EOPNOTSUPP;
6923
6924 // Check whether there has already been a delegate UID configured, if so, perform
6925 // cleanup and disallow bypassing VPN for that UID if no other caller is delegating
6926 // this UID.
6927 // TODO: consider using exceptions instead of errnos.
6928 final int errno = nai.removeCaptivePortalDelegateUid(this);
6929 if (errno != 0) return errno;
6930
6931 // If uid == INVALID_UID, we are done.
6932 if (uid == INVALID_UID) return 0;
6933 return nai.setCaptivePortalDelegateUid(this, uid);
6934 }
6935
6936 @Override
6937 public void setDelegateUid(int uid, @NonNull final IBinder callerBinder,
6938 @NonNull final IIntResultListener listener) {
6939 Objects.requireNonNull(callerBinder);
6940 Objects.requireNonNull(listener);
6941 enforceAnyPermissionOf(mContext, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
6942
6943 mHandler.post(() -> {
6944 final int errno = handleSetDelegateUid(uid, callerBinder);
6945 try {
6946 listener.onResult(errno);
6947 } catch (RemoteException e) {
6948 // remote has died, nothing to do.
6949 }
6950 });
6951 }
6952
Chiachang Wang938bfba2020-01-09 13:50:55 +08006953 @Nullable
6954 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
6955 // getNetworkAgentInfoForNetwork is thread-safe
6956 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6957 if (nai == null) return null;
6958
6959 // nai.networkMonitor() is thread-safe
6960 return nai.networkMonitor();
6961 }
Patrick Rohr7d6dfd52024-12-05 04:06:53 +00006962
6963 @Override
6964 public void binderDied() {
6965 // Cleanup invalid UID and restore the VPN bypass rule. Because mDelegateUidCaller is
6966 // never reset, it cannot be null in this context.
6967 mHandler.post(() -> handleSetDelegateUid(INVALID_UID, mDelegateUidCaller));
6968 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006969 }
6970
Hugo Benichic9048bc2016-09-14 23:23:08 +00006971 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006972 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09006973 }
6974
Chalard Jean020b93a2022-09-01 13:20:14 +09006975 private boolean activelyPreferBadWifi() {
6976 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
6977 }
6978
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09006979 /**
6980 * Return whether the device should maintain continuous, working connectivity by switching away
6981 * from WiFi networks having no connectivity.
6982 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
6983 */
6984 public boolean shouldAvoidBadWifi() {
Junyu Lai71b51532024-02-01 10:39:01 +08006985 if (!hasNetworkStackPermission()) {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09006986 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
6987 }
6988 return avoidBadWifi();
6989 }
6990
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006991 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09006992 ensureRunningOnConnectivityServiceThread();
6993 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09006994 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jean2f52a0e2025-03-21 10:14:28 +09006995 forEachNetworkAgentInfo(nai -> {
Chalard Jean142f0fe2021-03-31 23:19:05 +09006996 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09006997 if (avoidBadWifi) {
6998 // If the device is now avoiding bad wifi, remove notifications that might have
6999 // been put up when the device didn't.
7000 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
7001 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +09007002 });
Chalard Jeanbb902a52021-08-18 01:35:19 +09007003 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
7004 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
7005 for (final NetworkOfferInfo noi : offersToUpdate) {
7006 updateOfferScore(noi.offer);
7007 }
Chalard Jean020b93a2022-09-01 13:20:14 +09007008 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007009 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09007010 }
7011
Erik Kline95ecfee2016-10-02 18:02:14 +09007012 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09007013 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09007014 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09007015 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09007016 if (!configRestrict) {
7017 pw.println("Bad Wi-Fi avoidance: unrestricted");
7018 return;
7019 }
7020
7021 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
7022 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09007023 pw.println("Config restrict: " + configRestrict);
7024 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09007025
Chalard Jeane0fdea32022-09-14 21:44:22 +09007026 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09007027 String description;
7028 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09007029 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09007030 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09007031 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09007032 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09007033 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09007034 description = "avoid";
7035 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09007036 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09007037 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09007038 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00007039
7040 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
7041 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09007042 if (null == configValue) {
7043 description = "unset";
7044 } else if (configValue) {
7045 description = "force true";
7046 } else {
7047 description = "force false";
7048 }
7049 pw.println("Actively prefer bad wifi conf: " + description);
7050 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09007051 pw.println("Network overrides:");
7052 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09007053 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09007054 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09007055 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09007056 }
7057 }
7058 pw.decreaseIndent();
7059 pw.decreaseIndent();
7060 }
7061
paulhu7746e4e2020-06-09 19:07:03 +08007062 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
7063 // unify the method.
7064 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
7065 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
7066 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
7067 return settingsComponent != null
7068 ? settingsComponent.getPackageName() : "com.android.settings";
7069 }
7070
lucaslinb1e8e382019-01-24 15:55:30 +08007071 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007072 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09007073 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007074 switch (type) {
7075 case NO_INTERNET:
7076 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09007077 // High priority because it is only displayed for explicitly selected networks.
7078 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007079 break;
lucasline117e2e2019-10-22 18:27:33 +08007080 case PRIVATE_DNS_BROKEN:
7081 action = Settings.ACTION_WIRELESS_SETTINGS;
7082 // High priority because we should let user know why there is no internet.
7083 highPriority = true;
7084 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007085 case LOST_INTERNET:
7086 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09007087 // High priority because it could help the user avoid unexpected data usage.
7088 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007089 break;
lucaslin2240ef62019-03-12 13:08:03 +08007090 case PARTIAL_CONNECTIVITY:
7091 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09007092 // Don't bother the user with a high-priority notification if the network was not
7093 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007094 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08007095 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007096 default:
Aaron Huang6616df32020-10-30 22:04:25 +08007097 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007098 return;
7099 }
7100
7101 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08007102 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08007103 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08007104 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08007105 // Some OEMs have their own Settings package. Thus, need to get the current using
7106 // Settings package name instead of just use default name "com.android.settings".
7107 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
7108 intent.setClassName(settingsPkgName,
7109 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08007110 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007111
paulhu2af50222020-10-11 22:52:27 +08007112 PendingIntent pendingIntent = PendingIntent.getActivity(
7113 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08007114 0 /* requestCode */,
7115 intent,
paulhu2af50222020-10-11 22:52:27 +08007116 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09007117
Serik Beketayevec8ad212020-12-07 22:43:07 -08007118 mNotifier.showNotification(
7119 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007120 }
7121
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09007122 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
7123 // Don't prompt if the network is validated, and don't prompt on captive portals
7124 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09007125 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09007126 return false;
7127 }
7128
7129 // If a network has partial connectivity, always prompt unless the user has already accepted
7130 // partial connectivity and selected don't ask again. This ensures that if the device
7131 // automatically connects to a network that has partial Internet access, the user will
7132 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09007133 // because we have prompted them.
7134 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09007135 return true;
7136 }
7137
7138 // If a network has no Internet access, only prompt if the network was explicitly selected
7139 // and if the user has not already told us to use the network regardless of whether it
7140 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007141 if (nai.networkAgentConfig.explicitlySelected
7142 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09007143 return true;
7144 }
7145
7146 return false;
7147 }
7148
Chalard Jean5fb43c72022-09-08 19:03:14 +09007149 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
7150 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09007151
Chalard Jean5fb43c72022-09-08 19:03:14 +09007152 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
7153 if (null == nai) return;
7154
7155 if (nai.setEvaluated()) {
7156 // If setEvaluated() returned true, the network never had any form of connectivity.
7157 // This may have an impact on request matching if bad WiFi avoidance is off and the
7158 // network was found not to have Internet access.
7159 nai.updateScoreForNetworkAgentUpdate();
7160 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09007161
7162 // Also, if this is WiFi and it should be preferred actively, now is the time to
7163 // prompt the user that they walked past and connected to a bad WiFi.
7164 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
7165 && !avoidBadWifi()
7166 && activelyPreferBadWifi()) {
7167 // The notification will be removed if the network validates or disconnects.
7168 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
7169 return;
7170 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09007171 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09007172
Chalard Jean5fb43c72022-09-08 19:03:14 +09007173 if (!shouldPromptUnvalidated(nai)) return;
7174
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09007175 // Stop automatically reconnecting to this network in the future. Automatically connecting
7176 // to a network that provides no or limited connectivity is not useful, because the user
7177 // cannot use that network except through the notification shown by this method, and the
7178 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007179 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09007180
Chalard Jean254bd162022-08-25 13:04:51 +09007181 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08007182 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08007183 } else {
7184 showNetworkNotification(nai, NotificationType.NO_INTERNET);
7185 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007186 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09007187
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007188 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
7189 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09007190 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07007191
lucaslin2240ef62019-03-12 13:08:03 +08007192 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7193 return;
7194 }
7195
7196 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08007197 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09007198 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09007199 }
7200
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09007201 @Override
7202 public int getMultipathPreference(Network network) {
7203 enforceAccessPermission();
7204
7205 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06007206 if (nai != null && nai.networkCapabilities
7207 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09007208 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
7209 }
7210
Aaron Huang9a57acf2020-12-08 10:03:29 +08007211 final NetworkPolicyManager netPolicyManager =
7212 mContext.getSystemService(NetworkPolicyManager.class);
7213
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09007214 final long token = Binder.clearCallingIdentity();
7215 final int networkPreference;
7216 try {
7217 networkPreference = netPolicyManager.getMultipathPreference(network);
7218 } finally {
7219 Binder.restoreCallingIdentity(token);
7220 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08007221 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09007222 return networkPreference;
7223 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09007224 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
7225 }
7226
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007227 @Override
7228 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09007229 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007230 }
7231
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07007232 private class InternalHandler extends Handler {
7233 public InternalHandler(Looper looper) {
7234 super(looper);
7235 }
7236
7237 @Override
7238 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07007239 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07007240 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07007241 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09007242 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07007243 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07007244 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07007245 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09007246 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07007247 break;
7248 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08007249 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08007250 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08007251 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04007252 break;
7253 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007254 case EVENT_REGISTER_NETWORK_PROVIDER: {
7255 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007256 break;
7257 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007258 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
7259 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007260 break;
7261 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007262 case EVENT_REGISTER_NETWORK_OFFER: {
7263 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
7264 break;
7265 }
7266 case EVENT_UNREGISTER_NETWORK_OFFER: {
7267 final NetworkOfferInfo offer =
7268 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
7269 if (null != offer) {
Patrick Rohre7a4b082024-12-17 19:02:11 -08007270 handleUnregisterNetworkOffer(offer, true /* releaseReservations */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007271 }
7272 break;
7273 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007274 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007275 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
7276 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
7277 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007278 break;
7279 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007280 case EVENT_REGISTER_NETWORK_REQUEST:
7281 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09007282 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007283 break;
7284 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04007285 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
7286 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007287 handleRegisterNetworkRequestWithIntent(msg);
7288 break;
7289 }
Erik Kline155a59a2015-11-25 12:49:38 +09007290 case EVENT_TIMEOUT_NETWORK_REQUEST: {
7291 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
7292 handleTimedOutNetworkRequest(nri);
7293 break;
7294 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007295 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
7296 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
7297 break;
7298 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007299 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08007300 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
7301 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007302 break;
7303 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09007304 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09007305 Network network = (Network) msg.obj;
7306 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09007307 break;
7308 }
lucaslin2240ef62019-03-12 13:08:03 +08007309 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
7310 Network network = (Network) msg.obj;
7311 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
7312 toBool(msg.arg2));
7313 break;
7314 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09007315 case EVENT_SET_AVOID_UNVALIDATED: {
7316 handleSetAvoidUnvalidated((Network) msg.obj);
7317 break;
7318 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09007319 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
7320 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09007321 break;
7322 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007323 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
7324 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09007325 break;
7326 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00007327 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
7328 // handler thread.
7329 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007330 mKeepaliveTracker.handleStartKeepalive(msg);
7331 break;
7332 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00007333 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09007334 final AutomaticOnOffKeepalive ki =
7335 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
7336 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00007337
chiachangwang676c84e2023-02-14 09:22:05 +00007338 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09007339 final Network network = ki.getNetwork();
Chalard Jean2f52a0e2025-03-21 10:14:28 +09007340 final boolean networkFound =
7341 anyNetworkAgentInfo(n -> n.network.equals(network));
chiachangwang9ef4ffe2023-01-18 01:19:27 +00007342
7343 // If the network no longer exists, then the keepalive should have been
7344 // cleaned up already. There is no point trying to resume keepalives.
7345 if (!networkFound) return;
7346
Chalard Jean2f52a0e2025-03-21 10:14:28 +09007347 final boolean underpinnedNetworkFound = anyNetworkAgentInfo(
7348 n -> n.everConnected() && n.network.equals(underpinnedNetwork));
chiachangwang676c84e2023-02-14 09:22:05 +00007349 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09007350 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wangac2e8f32024-01-18 12:55:11 +00007351 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00007352 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00007353 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09007354 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00007355 }
7356 break;
7357 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007358 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08007359 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09007360 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
7361 (IBinder) msg.obj);
7362 if (ki == null) {
7363 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00007364 return;
7365 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09007366 final int reason = msg.arg2;
7367 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007368 break;
7369 }
Cody Kestingf1120be2020-08-03 18:01:40 -07007370 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
7371 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
7372 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09007373 break;
7374 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09007375 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
7376 handlePrivateDnsSettingsChanged();
7377 break;
dalyk1720e542018-03-05 12:42:22 -05007378 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
7379 handlePrivateDnsValidationUpdate(
7380 (PrivateDnsValidationUpdate) msg.obj);
7381 break;
Motomu Utsumid20727f2024-05-23 21:44:40 +09007382 case EVENT_BLOCKED_REASONS_CHANGED:
7383 handleBlockedReasonsChanged((List) msg.obj);
junyulaif2c67e42018-08-07 19:50:45 +08007384 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007385 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
7386 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
7387 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007388 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09007389 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
7390 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007391 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08007392 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007393 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007394 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09007395 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
7396 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007397 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08007398 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007399 }
lucaslin1193a5d2021-01-21 02:04:15 +08007400 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09007401 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09007402 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08007403 break;
paulhu51f77dc2021-06-07 02:34:20 +00007404 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
7405 handleMobileDataPreferredUidsChanged();
7406 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08007407 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
7408 final long timeMs = ((Long) msg.obj).longValue();
7409 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
7410 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01007411 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
7412 handleIngressRateLimitChanged();
7413 break;
Hansen Kurli55396972022-10-28 03:31:17 +00007414 case EVENT_USER_DOES_NOT_WANT:
7415 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
7416 if (nai == null) break;
7417 nai.onPreventAutomaticReconnect();
Chalard Jean9fdc9882025-03-21 10:13:47 +09007418 if (mQueueNetworkAgentEventsInSystemServer) {
7419 disconnectAndDestroyNetwork(nai);
7420 } else {
7421 nai.disconnect();
7422 }
Hansen Kurli55396972022-10-28 03:31:17 +00007423 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00007424 case EVENT_SET_VPN_NETWORK_PREFERENCE:
7425 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
7426 break;
chiachangwange0192a72023-02-06 13:25:01 +00007427 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
7428 final long time = ((Long) msg.obj).longValue();
7429 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
7430 break;
7431 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00007432 case EVENT_UID_FROZEN_STATE_CHANGED:
7433 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
7434 handleFrozenUids(args.mUids, args.mFrozenStates);
7435 break;
Motomu Utsumiff555a72024-05-23 23:22:40 +09007436 case EVENT_UPDATE_FIREWALL_DESTROY_SOCKET_REASONS:
7437 handleUpdateFirewallDestroySocketReasons((List) msg.obj);
7438 break;
7439 case EVENT_CLEAR_FIREWALL_DESTROY_SOCKET_REASONS:
7440 handleClearFirewallDestroySocketReasons(msg.arg1);
7441 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08007442 }
7443 }
7444 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08007445
Lorenzo Colittid6459092016-07-04 12:55:44 +09007446 @Override
markchien5776f962019-12-16 20:15:20 +08007447 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08007448 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08007449 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08007450 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
7451 Context.TETHERING_SERVICE);
7452 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08007453 }
7454
Lorenzo Colittid6459092016-07-04 12:55:44 +09007455 @Override
markchien5776f962019-12-16 20:15:20 +08007456 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08007457 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08007458 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08007459 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
7460 Context.TETHERING_SERVICE);
7461 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08007462 }
7463
Lorenzo Colittid6459092016-07-04 12:55:44 +09007464 @Override
markchien5776f962019-12-16 20:15:20 +08007465 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08007466 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08007467 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08007468 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
7469 Context.TETHERING_SERVICE);
7470 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08007471 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08007472
markchien5776f962019-12-16 20:15:20 +08007473
Lorenzo Colittid6459092016-07-04 12:55:44 +09007474 @Override
markchien5776f962019-12-16 20:15:20 +08007475 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08007476 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08007477 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08007478 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
7479 Context.TETHERING_SERVICE);
7480
7481 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08007482 }
7483
Lorenzo Colittid6459092016-07-04 12:55:44 +09007484 @Override
markchien5776f962019-12-16 20:15:20 +08007485 @Deprecated
7486 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08007487 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08007488 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
7489 Context.TETHERING_SERVICE);
7490
7491 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07007492 }
7493
Udam Saini8f7d6a72017-06-07 12:06:28 -07007494 @Override
markchien5776f962019-12-16 20:15:20 +08007495 @Deprecated
7496 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08007497 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08007498 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
7499 Context.TETHERING_SERVICE);
7500 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08007501 }
7502
Robert Greenwalte0b00512014-07-02 09:59:16 -07007503 // Called when we lose the default network and have no replacement yet.
7504 // This will automatically be cleared after X seconds or a new default network
7505 // becomes CONNECTED, whichever happens first. The timer is started by the
7506 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09007507 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07007508 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09007509 if (mNetTransitionWakeLock.isHeld()) {
7510 return;
7511 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07007512 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09007513 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
7514 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07007515 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09007516 mWakelockLogs.log("ACQUIRE for " + forWhom);
7517 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007518 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007519 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007520 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07007521 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07007522
Hugo Benichi471b62a2017-03-30 23:18:10 +09007523 // Called when we gain a new default network to release the network transition wakelock in a
7524 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
7525 // message is cancelled.
7526 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09007527 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09007528 if (!mNetTransitionWakeLock.isHeld()) {
7529 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09007530 }
7531 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09007532 // Cancel self timeout on wakelock hold.
7533 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
7534 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
7535 mHandler.sendMessageDelayed(msg, 1000);
7536 }
7537
7538 // Called when either message of ensureNetworkTransitionWakelock or
7539 // scheduleReleaseNetworkTransitionWakelock is processed.
7540 private void handleReleaseNetworkTransitionWakelock(int eventId) {
7541 String event = eventName(eventId);
7542 synchronized (this) {
7543 if (!mNetTransitionWakeLock.isHeld()) {
7544 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08007545 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09007546 return;
7547 }
7548 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09007549 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
7550 mTotalWakelockDurationMs += lockDuration;
7551 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
7552 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09007553 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09007554 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09007555 }
7556
Robert Greenwalt986c7412010-09-08 15:24:47 -07007557 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09007558 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07007559 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007560 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09007561 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04007562 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07007563 }
7564
Lorenzo Colittid6459092016-07-04 12:55:44 +09007565 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04007566 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04007567 enforceAccessPermission();
7568 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007569 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09007570 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08007571
7572 final NetworkAgentInfo nai;
7573 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09007574 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08007575 } else {
7576 nai = getNetworkAgentInfoForNetwork(network);
7577 }
Cody Kesting3d1df812020-06-25 11:13:39 -07007578
7579 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07007580 mHandler.obtainMessage(
7581 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09007582 }
Paul Jensen83f5d572014-08-29 09:54:01 -04007583
Hugo Benichid6b510a2017-04-06 17:22:18 +09007584 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07007585 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07007586 if (nai == null
7587 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07007588 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04007589 return;
7590 }
Paul Jensenb95d7952015-04-07 12:43:13 -04007591 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09007592 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07007593 mConnectivityDiagnosticsHandler.sendMessage(
7594 mConnectivityDiagnosticsHandler.obtainMessage(
7595 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
7596 new ReportedNetworkConnectivityInfo(
7597 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09007598 return;
7599 }
Paul Jensenb95d7952015-04-07 12:43:13 -04007600 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007601 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09007602 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04007603 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09007604 // Validating a network that has not yet connected could result in a call to
7605 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09007606 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09007607 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04007608 }
paulhu7aeba372020-12-30 00:42:19 +08007609 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
7610 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09007611 return;
7612 }
Cody Kestingf1120be2020-08-03 18:01:40 -07007613
7614 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
7615 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
7616 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
7617 // completed.
7618 mConnectivityDiagnosticsHandler.sendMessage(
7619 mConnectivityDiagnosticsHandler.obtainMessage(
7620 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
7621 new ReportedNetworkConnectivityInfo(
7622 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09007623 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007624 }
7625
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09007626 // TODO: call into netd.
7627 private boolean queryUserAccess(int uid, Network network) {
7628 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
7629 if (nai == null) return false;
7630
7631 // Any UID can use its default network.
7632 if (nai == getDefaultNetworkForUid(uid)) return true;
7633
7634 // Privileged apps can use any network.
7635 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
7636 return true;
7637 }
7638
7639 // An unprivileged UID can use a VPN iff the VPN applies to it.
7640 if (nai.isVPN()) {
7641 return nai.networkCapabilities.appliesToUid(uid);
7642 }
7643
7644 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
7645 // sockets, i.e., if it is the owner.
7646 final NetworkAgentInfo vpn = getVpnForUid(uid);
7647 if (vpn != null && !vpn.networkAgentConfig.allowBypass
7648 && uid != vpn.networkCapabilities.getOwnerUid()) {
7649 return false;
7650 }
7651
7652 // The UID's permission must be at least sufficient for the network. Since the restricted
7653 // permission was already checked above, that just leaves background networks.
7654 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
7655 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
7656 }
7657
7658 // Unrestricted network. Anyone gets to use it.
7659 return true;
7660 }
7661
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007662 /**
7663 * Returns information about the proxy a certain network is using. If given a null network, it
7664 * it will return the proxy for the bound network for the caller app or the default proxy if
7665 * none.
7666 *
7667 * @param network the network we want to get the proxy information for.
7668 * @return Proxy information if a network has a proxy configured, or otherwise null.
7669 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09007670 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04007671 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09007672 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04007673 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007674 if (network == null) {
7675 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007676 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007677 true);
7678 if (activeNetwork == null) {
7679 return null;
7680 }
7681 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09007682 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007683 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
7684 // caller may not have.
7685 return getLinkPropertiesProxyInfo(network);
7686 }
7687 // No proxy info available if the calling UID does not have network access.
7688 return null;
7689 }
7690
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007691
7692 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04007693 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
7694 if (nai == null) return null;
7695 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007696 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
7697 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04007698 }
7699 }
7700
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09007701 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09007702 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08007703 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09007704 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007705 }
7706
Chalard Jean777e2e52018-06-07 18:02:37 +09007707 @Override
7708 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04007709 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09007710 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007711 }
7712
Aaron Huang9fe47be2021-06-08 13:11:45 +08007713 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09007714 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08007715 final NetworkAgentInfo nai = getDefaultNetwork();
7716 // TODO : this method should check that net == nai.network, unfortunately at this point
7717 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
7718 // is only ever installed on the default network so in practice this is okay.
7719 if (null == nai) return;
7720 // PAC proxies only work on the default network. Therefore, only the default network
7721 // should have its link properties fixed up for PAC proxies.
7722 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
7723 if (nai.everConnected()) {
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +09007724 notifyNetworkCallbacks(nai, CALLBACK_IP_CHANGED);
Aaron Huang9fe47be2021-06-08 13:11:45 +08007725 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007726 }
7727
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007728 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
7729 // when any network changes proxy.
7730 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
7731 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08007732 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
7733 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05007734 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
7735
Chalard Jean7d97afc2018-06-07 17:41:29 +09007736 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09007737 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05007738 }
7739 }
7740
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007741 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09007742 final private HashMap<Uri, Integer> mUriEventMap;
7743 final private Context mContext;
7744 final private Handler mHandler;
7745
7746 SettingsObserver(Context context, Handler handler) {
7747 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007748 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09007749 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007750 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007751 }
7752
Erik Kline05f2b402015-04-30 12:58:40 +09007753 void observe(Uri uri, int what) {
7754 mUriEventMap.put(uri, what);
7755 final ContentResolver resolver = mContext.getContentResolver();
7756 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007757 }
7758
7759 @Override
7760 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08007761 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09007762 }
7763
7764 @Override
7765 public void onChange(boolean selfChange, Uri uri) {
7766 final Integer what = mUriEventMap.get(uri);
7767 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007768 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09007769 } else {
7770 loge("No matching event to send for URI=" + uri);
7771 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007772 }
7773 }
Wink Savillee70c6f52010-12-03 12:01:38 -08007774
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07007775 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08007776 Log.d(TAG, s);
7777 }
7778
7779 private static void logw(String s) {
7780 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08007781 }
7782
Daniel Brightf9e945b2020-06-15 16:10:01 -07007783 private static void logwtf(String s) {
7784 Log.wtf(TAG, s);
7785 }
7786
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09007787 private static void logwtf(String s, Throwable t) {
7788 Log.wtf(TAG, s, t);
7789 }
7790
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07007791 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08007792 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08007793 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07007794
Hugo Benichi39621362017-02-11 17:04:43 +09007795 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08007796 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09007797 }
7798
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07007799 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08007800 * Return the information of all ongoing VPNs.
7801 *
7802 * <p>This method is used to update NetworkStatsService.
7803 *
7804 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08007805 */
junyulai2050bed2021-01-23 09:46:34 +08007806 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08007807 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09007808 if (mLockdownEnabled) {
7809 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08007810 }
junyulai2050bed2021-01-23 09:46:34 +08007811 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Chalard Jean2f52a0e2025-03-21 10:14:28 +09007812 forEachNetworkAgentInfo(nai -> {
junyulai2050bed2021-01-23 09:46:34 +08007813 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09007814 if (info != null) {
7815 infoList.add(info);
7816 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +09007817 });
junyulai2050bed2021-01-23 09:46:34 +08007818 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08007819 }
7820
7821 /**
7822 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00007823 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08007824 */
junyulai2050bed2021-01-23 09:46:34 +08007825 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007826 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08007827 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
7828 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09007829 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
7830 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
7831 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08007832 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
7833 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00007834 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00007835 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08007836 }
7837 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007838
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007839 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007840
7841 List<String> interfaces = new ArrayList<>();
7842 for (Network network : underlyingNetworks) {
7843 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
7844 if (underlyingNai == null) continue;
7845 LinkProperties lp = underlyingNai.linkProperties;
7846 for (String iface : lp.getAllInterfaceNames()) {
7847 if (!TextUtils.isEmpty(iface)) {
7848 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00007849 }
7850 }
Benedict Wong34857f82019-06-12 17:46:15 +00007851 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007852
7853 if (interfaces.isEmpty()) return null;
7854
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007855 // Must be non-null or NetworkStatsService will crash.
7856 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
7857 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08007858 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08007859 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007860
junyulai2050bed2021-01-23 09:46:34 +08007861 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
7862 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08007863 }
7864
James Mattisd31bdfa2020-12-23 16:37:26 -08007865 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08007866 private Network[] underlyingNetworksOrDefault(final int ownerUid,
7867 Network[] underlyingNetworks) {
7868 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007869 if (underlyingNetworks == null && defaultNetwork != null) {
7870 // null underlying networks means to track the default.
7871 underlyingNetworks = new Network[] { defaultNetwork };
7872 }
7873 return underlyingNetworks;
7874 }
7875
7876 // Returns true iff |network| is an underlying network of |nai|.
7877 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
7878 // TODO: support more than one level of underlying networks, either via a fixed-depth search
7879 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09007880 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08007881 final Network[] underlying = underlyingNetworksOrDefault(
7882 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007883 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007884 }
7885
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007886 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007887 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007888 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007889 * When underlying networks change, such networks may have to update capabilities to reflect
7890 * things like the metered bit, their transports, and so on. The capabilities are calculated
7891 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007892 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007893 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007894 ensureRunningOnConnectivityServiceThread();
Chalard Jean2f52a0e2025-03-21 10:14:28 +09007895 forEachNetworkAgentInfo(nai -> {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007896 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007897 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007898 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +09007899 });
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007900 }
7901
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007902 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
7903 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
7904 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
7905 // a VPN is not up.
7906 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
7907 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
7908 for (UidRange range : blockedUidRanges) {
7909 if (range.contains(uid)) return true;
7910 }
7911 return false;
7912 }
7913
7914 @Override
7915 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08007916 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007917 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
7918 encodeBool(requireVpn), 0 /* arg2 */, ranges));
7919 }
7920
7921 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
7922 if (DBG) {
7923 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
7924 + Arrays.toString(ranges));
7925 }
7926 // Cannot use a Set since the list of UID ranges might contain duplicates.
7927 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
7928 for (int i = 0; i < ranges.length; i++) {
7929 if (requireVpn) {
7930 newVpnBlockedUidRanges.add(ranges[i]);
7931 } else {
7932 newVpnBlockedUidRanges.remove(ranges[i]);
7933 }
7934 }
7935
7936 try {
7937 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
7938 } catch (RemoteException | ServiceSpecificException e) {
7939 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
7940 + Arrays.toString(ranges) + "): netd command failed: " + e);
7941 }
7942
Chalard Jeandf29a852023-05-29 17:02:43 +09007943 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00007944 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
7945 }
7946
Chalard Jean2f52a0e2025-03-21 10:14:28 +09007947 forEachNetworkAgentInfo(nai -> {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007948 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00007949 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
7950 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Chalard Jean2f52a0e2025-03-21 10:14:28 +09007951 });
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007952
7953 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
7954 }
7955
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07007956 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007957 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08007958 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007959 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01007960 }
7961
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007962 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
7963 return mLockdownEnabled
Lorenzo Colittifd89cf52025-03-18 13:13:45 +09007964 && isLegacyVpn(nai)
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007965 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00007966 }
7967
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007968 private NetworkAgentInfo getLegacyLockdownNai() {
7969 if (!mLockdownEnabled) {
7970 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00007971 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007972 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007973 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
7974 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00007975
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007976 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007977 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
7978 // a local variable. There is no need to make a copy because its contents cannot change.
7979 final Network[] underlying = nai.declaredUnderlyingNetworks;
7980 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007981 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007982 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007983
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007984 // The legacy lockdown VPN always uses the default network.
7985 // If the VPN's underlying network is no longer the current default network, it means that
7986 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007987 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
7988 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007989 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007990 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007991 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007992 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007993
7994 return nai;
7995 };
7996
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007997 // TODO: move all callers to filterForLegacyLockdown and delete this method.
7998 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
7999 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09008000 private DetailedState getLegacyLockdownState(DetailedState origState) {
8001 if (origState != DetailedState.CONNECTED) {
8002 return origState;
8003 }
8004 return (mLockdownEnabled && getLegacyLockdownNai() == null)
8005 ? DetailedState.CONNECTING
8006 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00008007 }
8008
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09008009 private void filterForLegacyLockdown(NetworkInfo ni) {
8010 if (!mLockdownEnabled || !ni.isConnected()) return;
8011 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
8012 // state of its VPN. This is to ensure that when an underlying network connects, apps will
8013 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
8014 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
8015 // network, this time with a state of CONNECTED.
8016 //
8017 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
8018 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
8019 // is not too far off the truth, since an always-on VPN, when not connected, is always
8020 // trying to reconnect.
8021 if (getLegacyLockdownNai() == null) {
8022 ni.setDetailedState(DetailedState.CONNECTING, "", null);
8023 }
8024 }
8025
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00008026 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07008027 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04008028 String action) {
paulhu8e96a752019-08-12 16:25:11 +08008029 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09008030 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
8031 return;
8032 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04008033 final long ident = Binder.clearCallingIdentity();
8034 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09008035 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008036 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09008037 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04008038 } finally {
8039 Binder.restoreCallingIdentity(ident);
8040 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07008041 }
Wink Savillecb117d32013-08-29 14:57:08 -07008042
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07008043 @Override
8044 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01008045 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07008046 final long ident = Binder.clearCallingIdentity();
8047 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07008048 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09008049 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07008050 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
8051 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08008052 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07008053 } finally {
8054 Binder.restoreCallingIdentity(ident);
8055 }
8056 }
8057
James Mattis02220e22021-03-13 19:27:21 -08008058 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08008059 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
8060 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
8061 }
Chalard Jeane0abd522023-01-23 16:47:43 +09008062 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07008063 }
8064
James Mattis02220e22021-03-13 19:27:21 -08008065 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09008066 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08008067 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08008068 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
8069 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09008070 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08008071 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
8072 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
8073 }
junyulaid91e7052020-08-28 13:44:33 +08008074 }
8075
James Mattis02220e22021-03-13 19:27:21 -08008076 private void onPackageChanged(@NonNull final String packageName) {
8077 // This is necessary in case a package is added or removed, but also when it's replaced to
8078 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
8079 // as one in the preferences, then it should follow the same routing as that other package,
8080 // which means updating the rules is never to be needed in this case (whether it joins or
8081 // leaves a UID with a preference).
8082 if (isMappedInOemNetworkPreference(packageName)) {
8083 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
8084 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09008085
8086 // Invalidates cache entry when the package is updated.
8087 synchronized (mSelfCertifiedCapabilityCache) {
8088 mSelfCertifiedCapabilityCache.remove(packageName);
8089 }
James Mattis02220e22021-03-13 19:27:21 -08008090 }
8091
8092 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07008093 @Override
8094 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09008095 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07008096 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09008097 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08008098
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09008099 // User should be filled for below intents, check the existence.
8100 if (user == null) {
8101 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
8102 return;
8103 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07008104
Lorenzo Colitticd675292021-02-04 17:32:07 +09008105 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09008106 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07008107 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09008108 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09008109 } else {
junyulaid91e7052020-08-28 13:44:33 +08008110 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07008111 }
8112 }
8113 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07008114
James Mattis02220e22021-03-13 19:27:21 -08008115 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
8116 @Override
8117 public void onReceive(Context context, Intent intent) {
8118 ensureRunningOnConnectivityServiceThread();
8119 switch (intent.getAction()) {
8120 case Intent.ACTION_PACKAGE_ADDED:
8121 case Intent.ACTION_PACKAGE_REMOVED:
8122 case Intent.ACTION_PACKAGE_REPLACED:
8123 onPackageChanged(intent.getData().getSchemeSpecificPart());
8124 break;
8125 default:
8126 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
8127 }
8128 }
8129 };
8130
Junyu Lai38c75032023-12-04 07:52:19 +00008131 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
8132 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
8133 @Override
8134 public void onReceive(Context context, Intent intent) {
8135 if (mDeps.isAtLeastV()) {
8136 throw new IllegalStateException(
8137 "data saver status should be updated from platform");
8138 }
8139 ensureRunningOnConnectivityServiceThread();
8140 switch (intent.getAction()) {
8141 case ACTION_RESTRICT_BACKGROUND_CHANGED:
8142 // If the uid is present in the deny list, the API will consistently
8143 // return ENABLED. To retrieve the global switch status, the system
8144 // uid is chosen because it will never be included in the deny list.
8145 final int dataSaverForSystemUid =
8146 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
8147 final boolean isDataSaverEnabled = (dataSaverForSystemUid
8148 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
8149 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
8150 break;
8151 default:
8152 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
8153 }
8154 }
8155 };
8156
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008157 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008158 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008159
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008160 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008161 public final String name;
8162 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008163 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008164 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008165
lifraf3a3492021-03-10 13:58:14 +08008166 NetworkProviderInfo(String name, Messenger messenger, int providerId,
8167 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008168 this.name = name;
8169 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008170 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008171 mDeathRecipient = deathRecipient;
8172
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09008173 if (mDeathRecipient == null) {
8174 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008175 }
8176 }
8177
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09008178 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09008179 try {
8180 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
8181 } catch (RemoteException e) {
8182 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008183 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09008184 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008185 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008186
Patrick Rohr8b42a112024-12-23 14:00:07 -08008187 private void ensureAllNetworkRequestsHaveSupportedType(List<NetworkRequest> requests) {
8188 final boolean isMultilayerRequest = requests.size() > 1;
James Mattis4fce5d12020-11-12 15:53:42 -08008189 for (int i = 0; i < requests.size(); i++) {
Patrick Rohr8b42a112024-12-23 14:00:07 -08008190 ensureNetworkRequestHasSupportedType(requests.get(i), isMultilayerRequest);
James Mattis4fce5d12020-11-12 15:53:42 -08008191 }
8192 }
8193
Patrick Rohr8b42a112024-12-23 14:00:07 -08008194 private void ensureNetworkRequestHasSupportedType(NetworkRequest request,
8195 boolean isMultilayerRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09008196 if (request.type == NetworkRequest.Type.NONE) {
8197 throw new IllegalArgumentException(
8198 "All NetworkRequests in ConnectivityService must have a type");
8199 }
Patrick Rohr8b42a112024-12-23 14:00:07 -08008200 if (isMultilayerRequest && request.type == NetworkRequest.Type.RESERVATION) {
8201 throw new IllegalArgumentException(
8202 "Reservation requests are not supported in multilayer request");
8203 }
Lorenzo Colitti70964d32016-07-05 01:22:13 +09008204 }
8205
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07008206 /**
8207 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08008208 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07008209 */
James Mattis258ea3c2020-11-15 15:04:40 -08008210 @VisibleForTesting
8211 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08008212 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
8213 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08008214 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08008215
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +09008216 /**
8217 * List of callbacks that are queued for sending later when the requesting app is unfrozen.
8218 *
8219 * <p>There may typically be hundreds of NetworkRequestInfo, so a memory-efficient structure
8220 * (just an int[]) is used to keep queued callbacks. This reduces the number of object
8221 * references.
8222 *
8223 * <p>This is intended to be used with {@link CallbackQueue} which defines the internal
8224 * format.
8225 */
8226 @NonNull
8227 private int[] mQueuedCallbacks = new int[0];
8228
8229 private static final int MATCHED_NETID_NOT_FROZEN = -1;
8230
8231 /**
8232 * If this request was already satisfied by a network when the requesting UID was frozen,
8233 * the netId that was matched at that time. Otherwise, NETID_UNSET if no network was
8234 * satisfying this request when frozen (including if this is a listen and not a request),
8235 * and MATCHED_NETID_NOT_FROZEN if not frozen.
8236 */
8237 private int mMatchedNetIdWhenFrozen = MATCHED_NETID_NOT_FROZEN;
8238
James Mattisa076c532020-12-02 14:12:41 -08008239 // mSatisfier and mActiveRequest rely on one another therefore set them together.
8240 void setSatisfier(
8241 @Nullable final NetworkAgentInfo satisfier,
8242 @Nullable final NetworkRequest activeRequest) {
8243 mSatisfier = satisfier;
8244 mActiveRequest = activeRequest;
8245 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008246
James Mattisd31bdfa2020-12-23 16:37:26 -08008247 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008248 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09008249 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08008250 private NetworkAgentInfo mSatisfier;
8251 NetworkAgentInfo getSatisfier() {
8252 return mSatisfier;
8253 }
8254
8255 // The request in mRequests assigned to a network agent. This is null if none of the
8256 // requests in mRequests can be satisfied. This member has the constraint of only being
8257 // accessible on the handler thread.
8258 @Nullable
8259 private NetworkRequest mActiveRequest;
8260 NetworkRequest getActiveRequest() {
8261 return mActiveRequest;
8262 }
8263
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008264 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008265 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08008266 @Nullable
8267 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008268
8269 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08008270 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008271 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008272 final int mPid;
8273 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08008274 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08008275 @Nullable
8276 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008277
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09008278 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08008279 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09008280
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008281 // Effective UID of this request. This is different from mUid when a privileged process
8282 // files a request on behalf of another UID. This UID is used to determine blocked status,
8283 // UID matching, and so on. mUid above is used for permission checks and to enforce the
8284 // maximum limit of registered callbacks per UID.
8285 final int mAsUid;
8286
Motomu Utsumid20727f2024-05-23 21:44:40 +09008287 // Flag to indicate that uid of this nri is tracked for sending blocked status callbacks.
8288 // It is always true on V+ if mMessenger != null. As such, it's not strictly necessary.
8289 // it's used only as a safeguard to avoid double counting or leaking.
8290 boolean mUidTrackedForBlockedStatus;
8291
paulhu48291862021-07-14 14:53:57 +08008292 // Preference order of this request.
8293 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08008294
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09008295 final int mDeclaredMethodsFlags;
8296
James Mattis3ce3d3c2021-02-09 18:18:28 -08008297 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
8298 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
8299 // maintained for keying off of. This is only a concern when the original nri
8300 // mNetworkRequests changes which happens currently for apps that register callbacks to
8301 // track the default network. In those cases, the nri is updated to have mNetworkRequests
8302 // that match the per-app default nri that currently tracks the calling app's uid so that
8303 // callbacks are fired at the appropriate time. When the callbacks fire,
8304 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
8305 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
8306 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
8307 @NonNull
8308 private final NetworkRequest mNetworkRequestForCallback;
8309 NetworkRequest getNetworkRequestForCallback() {
8310 return mNetworkRequestForCallback;
8311 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008312
James Mattisd31bdfa2020-12-23 16:37:26 -08008313 /**
Patrick Rohr73eee542024-12-06 12:29:29 -08008314 * NetworkCapabilities that were created as part of a NetworkOffer in response to a
8315 * RESERVATION request. mReservedCapabilities is null if no current offer matches the
8316 * RESERVATION request or if the request is not a RESERVATION. Matching is based on
8317 * reservationId.
8318 */
8319 @Nullable
8320 private NetworkCapabilities mReservedCapabilities;
8321 @Nullable
8322 NetworkCapabilities getReservedCapabilities() {
8323 return mReservedCapabilities;
8324 }
8325
8326 void setReservedCapabilities(@NonNull NetworkCapabilities caps) {
8327 // This function can only be called once. NetworkCapabilities are never reset as the
8328 // reservation is released when the offer disappears.
8329 if (mReservedCapabilities != null) {
8330 logwtf("ReservedCapabilities can only be set once");
8331 }
8332 mReservedCapabilities = caps;
8333 }
8334
8335 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008336 * Get the list of UIDs this nri applies to.
8337 */
8338 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00008339 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08008340 // networkCapabilities.getUids() returns a defensive copy.
8341 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008342 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
8343 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08008344 }
8345
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008346 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
8347 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08008348 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08008349 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08008350 }
8351
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008352 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08008353 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08008354 @Nullable String callingAttributionTag, final int preferenceOrder) {
Patrick Rohr8b42a112024-12-23 14:00:07 -08008355 ensureAllNetworkRequestsHaveSupportedType(r);
James Mattis60b84b22020-11-03 15:54:33 -08008356 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008357 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008358 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08008359 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008360 mBinder = null;
8361 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008362 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008363 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09008364 mPerUidCounter = getRequestCounter(this);
Roshan Pius951c0032020-12-22 15:10:42 -08008365 /**
8366 * Location sensitive data not included in pending intent. Only included in
8367 * {@link NetworkCallback}.
8368 */
8369 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08008370 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08008371 mPreferenceOrder = preferenceOrder;
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09008372 mDeclaredMethodsFlags = DECLARED_METHODS_NONE;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008373 }
8374
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008375 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08008376 @Nullable final IBinder binder,
8377 @NetworkCallback.Flag int callbackFlags,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09008378 @Nullable String callingAttributionTag, int declaredMethodsFlags) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008379 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09008380 callingAttributionTag, declaredMethodsFlags);
James Mattis45d81842021-01-10 14:24:24 -08008381 }
8382
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008383 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08008384 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08008385 @Nullable final IBinder binder,
8386 @NetworkCallback.Flag int callbackFlags,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09008387 @Nullable String callingAttributionTag, int declaredMethodsFlags) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008388 super();
Patrick Rohr8b42a112024-12-23 14:00:07 -08008389 ensureAllNetworkRequestsHaveSupportedType(r);
James Mattis60b84b22020-11-03 15:54:33 -08008390 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008391 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08008392 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008393 mBinder = binder;
8394 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008395 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008396 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008397 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09008398 mPerUidCounter = getRequestCounter(this);
Roshan Pius951c0032020-12-22 15:10:42 -08008399 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08008400 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08008401 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09008402 mDeclaredMethodsFlags = declaredMethodsFlags;
James Mattisb1392002021-03-31 13:57:52 -07008403 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008404 }
8405
James Mattis3ce3d3c2021-02-09 18:18:28 -08008406 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
8407 @NonNull final List<NetworkRequest> r) {
8408 super();
Patrick Rohr8b42a112024-12-23 14:00:07 -08008409 ensureAllNetworkRequestsHaveSupportedType(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008410 mRequests = initializeRequests(r);
8411 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09008412 final NetworkAgentInfo satisfier = nri.getSatisfier();
8413 if (null != satisfier) {
8414 // If the old NRI was satisfied by an NAI, then it may have had an active request.
8415 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09008416 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09008417 // As this code creates a new NRI with a new set of requests, figure out which of
8418 // the list of requests should be the active request. It is always the first
8419 // request of the list that can be satisfied by the satisfier since the order of
8420 // requests is a priority order.
8421 // Note even in the presence of a satisfier there may not be an active request,
8422 // when the satisfier is the no-service network.
8423 NetworkRequest activeRequest = null;
8424 for (final NetworkRequest candidate : r) {
8425 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
8426 activeRequest = candidate;
8427 break;
8428 }
8429 }
8430 setSatisfier(satisfier, activeRequest);
8431 }
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +09008432 mMatchedNetIdWhenFrozen = nri.mMatchedNetIdWhenFrozen;
8433 mQueuedCallbacks = nri.mQueuedCallbacks;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008434 mMessenger = nri.mMessenger;
8435 mBinder = nri.mBinder;
8436 mPid = nri.mPid;
8437 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008438 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008439 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09008440 mPerUidCounter = nri.mPerUidCounter;
Roshan Pius951c0032020-12-22 15:10:42 -08008441 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008442 mCallingAttributionTag = nri.mCallingAttributionTag;
Motomu Utsumid20727f2024-05-23 21:44:40 +09008443 mUidTrackedForBlockedStatus = nri.mUidTrackedForBlockedStatus;
paulhu48291862021-07-14 14:53:57 +08008444 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09008445 mDeclaredMethodsFlags = nri.mDeclaredMethodsFlags;
James Mattisb1392002021-03-31 13:57:52 -07008446 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08008447 }
8448
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008449 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08008450 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08008451 }
8452
paulhue9913722021-05-26 15:19:20 +08008453 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08008454 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08008455 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08008456 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08008457 }
8458
James Mattis2516da32021-01-31 17:06:19 -08008459 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
8460 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
8461 // false.
8462 boolean isBeingSatisfied() {
8463 return (null != mSatisfier && null != mActiveRequest);
8464 }
8465
James Mattis3d229892020-11-16 16:46:28 -08008466 boolean isMultilayerRequest() {
8467 return mRequests.size() > 1;
8468 }
8469
James Mattis45d81842021-01-10 14:24:24 -08008470 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
8471 // Creating a defensive copy to prevent the sender from modifying the list being
8472 // reflected in the return value of this method.
8473 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08008474 return Collections.unmodifiableList(tempRequests);
8475 }
8476
James Mattisb1392002021-03-31 13:57:52 -07008477 void linkDeathRecipient() {
8478 if (null != mBinder) {
8479 try {
8480 mBinder.linkToDeath(this, 0);
8481 } catch (RemoteException e) {
8482 binderDied();
8483 }
8484 }
8485 }
8486
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008487 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07008488 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09008489 try {
8490 mBinder.unlinkToDeath(this, 0);
8491 } catch (NoSuchElementException e) {
8492 // Temporary workaround for b/194394697 pending analysis of additional logs
8493 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
8494 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008495 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008496 }
8497
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +09008498 /**
8499 * Called when this NRI is being frozen.
8500 *
8501 * <p>Calling this method multiple times when the NRI is frozen is fine. This may happen
8502 * if iterating through the NetworkRequest -> NRI map since there are duplicates in the
8503 * NRI values for multilayer requests. It may also happen if an app is frozen, killed,
8504 * restarted and refrozen since there is no callback sent when processes are killed, but in
8505 * that case the callbacks to the killed app do not matter.
8506 */
8507 void onFrozen() {
8508 if (mMatchedNetIdWhenFrozen != MATCHED_NETID_NOT_FROZEN) {
8509 // Already frozen
8510 return;
8511 }
8512 if (mSatisfier != null) {
8513 mMatchedNetIdWhenFrozen = mSatisfier.network.netId;
8514 } else {
8515 mMatchedNetIdWhenFrozen = NETID_UNSET;
8516 }
8517 }
8518
8519 boolean maybeQueueCallback(@NonNull NetworkAgentInfo nai, int callbackId) {
8520 if (mMatchedNetIdWhenFrozen == MATCHED_NETID_NOT_FROZEN) {
8521 return false;
8522 }
8523
8524 boolean ignoreThisCallback = false;
8525 final int netId = nai.network.netId;
8526 final CallbackQueue queue = new CallbackQueue(mQueuedCallbacks);
8527 // Based on the new callback, clear previous callbacks that are no longer necessary.
8528 // For example, if the network is lost, there is no need to send intermediate callbacks.
8529 switch (callbackId) {
8530 // PRECHECK is not an API and not very meaningful, do not deliver it for frozen apps
8531 // Networks are likely to already be lost when the app is unfrozen, also skip LOSING
8532 case CALLBACK_PRECHECK:
8533 case CALLBACK_LOSING:
8534 ignoreThisCallback = true;
8535 break;
8536 case CALLBACK_LOST:
8537 // All callbacks for this netId before onLost are unnecessary. And onLost itself
8538 // is also unnecessary if onAvailable was previously queued for this netId: the
8539 // Network just appeared and disappeared while the app was frozen.
8540 ignoreThisCallback = queue.hasCallback(netId, CALLBACK_AVAILABLE);
8541 queue.removeCallbacksForNetId(netId);
8542 break;
8543 case CALLBACK_AVAILABLE:
8544 if (mSatisfier != null) {
8545 // For requests that are satisfied by individual networks (not LISTEN), when
8546 // AVAILABLE is received, the request is matching a new Network, so previous
8547 // callbacks (for other Networks) are unnecessary.
8548 queue.clear();
8549 }
8550 break;
8551 case CALLBACK_SUSPENDED:
8552 case CALLBACK_RESUMED:
8553 if (queue.hasCallback(netId, CALLBACK_AVAILABLE)) {
8554 // AVAILABLE will already send the latest suspended status
8555 ignoreThisCallback = true;
8556 break;
8557 }
8558 // If SUSPENDED was queued, just remove it from the queue instead of sending
8559 // RESUMED; and vice-versa.
8560 final int otherCb = callbackId == CALLBACK_SUSPENDED
8561 ? CALLBACK_RESUMED
8562 : CALLBACK_SUSPENDED;
8563 ignoreThisCallback = queue.removeCallbacks(netId, otherCb);
8564 break;
8565 case CALLBACK_CAP_CHANGED:
8566 case CALLBACK_IP_CHANGED:
8567 case CALLBACK_LOCAL_NETWORK_INFO_CHANGED:
8568 case CALLBACK_BLK_CHANGED:
8569 ignoreThisCallback = queue.hasCallback(netId, CALLBACK_AVAILABLE);
8570 break;
8571 default:
8572 Log.wtf(TAG, "Unexpected callback type: "
8573 + ConnectivityManager.getCallbackName(callbackId));
8574 return false;
8575 }
8576
8577 if (!ignoreThisCallback) {
8578 // For non-listen (matching) callbacks, AVAILABLE can appear in the queue twice in a
8579 // row for the same network if the new AVAILABLE suppressed intermediate AVAILABLEs
8580 // for other networks. Example:
8581 // A is matched, app is frozen, B is matched, A is matched again (removes callbacks
8582 // for B), app is unfrozen.
8583 // In that case call AVAILABLE sub-callbacks to update state, but not AVAILABLE
8584 // itself.
8585 if (callbackId == CALLBACK_AVAILABLE && netId == mMatchedNetIdWhenFrozen) {
8586 // The queue should have been cleared here, since this is AVAILABLE on a
8587 // non-listen callback (mMatchedNetIdWhenFrozen is set).
8588 addAvailableSubCallbacks(nai, queue);
8589 } else {
8590 // When unfreezing, no need to send a callback multiple times for the same netId
8591 queue.removeCallbacks(netId, callbackId);
8592 // TODO: this code always adds the callback for simplicity. It would save
8593 // some CPU/memory if the code instead only added to the queue callbacks where
8594 // isCallbackOverridden=true, or which need to be in the queue because they
8595 // affect other callbacks that are overridden.
8596 queue.addCallback(netId, callbackId);
8597 }
8598 }
8599 // Instead of shrinking the queue, possibly reallocating, the NRI could keep the array
8600 // and length in memory for future adds, but this saves memory by avoiding the cost
8601 // of an extra member and of unused array length (there are often hundreds of NRIs).
Remi NGUYEN VANdfb15922024-08-02 19:25:04 +09008602 mQueuedCallbacks = queue.getMinimizedBackingArray();
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +09008603 return true;
8604 }
8605
8606 /**
8607 * Called when this NRI is being unfrozen to stop queueing, and send queued callbacks.
8608 *
8609 * <p>Calling this method multiple times when the NRI is unfrozen (for example iterating
8610 * through the NetworkRequest -> NRI map where there are duplicate values for multilayer
8611 * requests) is fine.
8612 */
8613 void sendQueuedCallbacks() {
8614 mMatchedNetIdWhenFrozen = MATCHED_NETID_NOT_FROZEN;
8615 if (mQueuedCallbacks.length == 0) {
8616 return;
8617 }
8618 new CallbackQueue(mQueuedCallbacks).forEach((netId, callbackId) -> {
8619 // For CALLBACK_LOST only, there will not be a NAI for the netId. Build and send the
8620 // callback directly.
8621 if (callbackId == CALLBACK_LOST) {
8622 if (isCallbackOverridden(CALLBACK_LOST)) {
8623 final Bundle cbBundle = makeCommonBundleForCallback(this,
8624 new Network(netId));
8625 callCallbackForRequest(this, CALLBACK_LOST, cbBundle, 0 /* arg1 */);
8626 }
8627 return; // Next item in forEach
8628 }
8629
8630 // Other callbacks should always have a NAI, because if a Network disconnects
8631 // LOST will be called, unless the request is no longer satisfied by that Network in
8632 // which case AVAILABLE will have been called for another Network. In both cases
8633 // previous callbacks are cleared.
8634 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
8635 if (nai == null) {
8636 Log.wtf(TAG, "Missing NetworkAgentInfo for net " + netId
8637 + " for callback " + callbackId);
8638 return; // Next item in forEach
8639 }
8640
8641 final int arg1 =
8642 callbackId == CALLBACK_AVAILABLE || callbackId == CALLBACK_BLK_CHANGED
8643 ? getBlockedState(nai, mAsUid)
8644 : 0;
8645 callCallbackForRequest(this, nai, callbackId, arg1);
8646 });
8647 mQueuedCallbacks = new int[0];
8648 }
8649
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +09008650 boolean isCallbackOverridden(int callbackId) {
8651 return !mUseDeclaredMethodsForCallbacksEnabled
8652 || (mDeclaredMethodsFlags & (1 << callbackId)) != 0;
8653 }
8654
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +09008655 /**
8656 * Queue all callbacks that are called by AVAILABLE, except onAvailable.
8657 *
8658 * <p>AVAILABLE may call SUSPENDED, CAP_CHANGED, IP_CHANGED, LOCAL_NETWORK_INFO_CHANGED,
8659 * and BLK_CHANGED, in this order.
8660 */
8661 private void addAvailableSubCallbacks(
8662 @NonNull NetworkAgentInfo nai, @NonNull CallbackQueue queue) {
8663 final boolean callSuspended =
8664 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8665 final boolean callLocalInfoChanged = nai.isLocalNetwork();
8666
8667 final int cbCount = 3 + (callSuspended ? 1 : 0) + (callLocalInfoChanged ? 1 : 0);
8668 // Avoid unnecessary re-allocations by reserving enough space for all callbacks to add.
8669 queue.ensureHasCapacity(cbCount);
8670 final int netId = nai.network.netId;
8671 if (callSuspended) {
8672 queue.addCallback(netId, CALLBACK_SUSPENDED);
8673 }
8674 queue.addCallback(netId, CALLBACK_CAP_CHANGED);
8675 queue.addCallback(netId, CALLBACK_IP_CHANGED);
8676 if (callLocalInfoChanged) {
8677 queue.addCallback(netId, CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
8678 }
8679 queue.addCallback(netId, CALLBACK_BLK_CHANGED);
8680 }
8681
paulhu48291862021-07-14 14:53:57 +08008682 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
8683 // Compare two preference orders.
8684 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08008685 }
8686
paulhu48291862021-07-14 14:53:57 +08008687 int getPreferenceOrderForNetd() {
8688 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
8689 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
8690 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08008691 }
paulhu48291862021-07-14 14:53:57 +08008692 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08008693 }
8694
Patrick Rohr73eee542024-12-06 12:29:29 -08008695 public int getReservationId() {
8696 // RESERVATIONs cannot be used in multilayer requests.
8697 if (isMultilayerRequest()) return RES_ID_UNSET;
8698 final NetworkRequest req = mRequests.get(0);
8699 // Non-reservation types return RES_ID_UNSET.
8700 return req.networkCapabilities.getReservationId();
8701 }
8702
James Mattis4fce5d12020-11-12 15:53:42 -08008703 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008704 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09008705 // As an immutable collection, mRequests cannot change by the time the
8706 // lambda is evaluated on the handler thread so calling .get() from a binder thread
8707 // is acceptable. Use handleReleaseNetworkRequest and not directly
8708 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
8709 // the app already unregistered the request.
8710 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
8711 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008712 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008713
James Mattis4fce5d12020-11-12 15:53:42 -08008714 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008715 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008716 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
8717 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08008718 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008719 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008720 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08008721 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08008722 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08008723 + " callback flags: " + mCallbackFlags
Motomu Utsumid20727f2024-05-23 21:44:40 +09008724 + " order: " + mPreferenceOrder
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09008725 + " isUidTracked: " + mUidTrackedForBlockedStatus
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +09008726 + " declaredMethods: " + declaredMethodsFlagsToString(mDeclaredMethodsFlags);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008727 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008728 }
8729
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +09008730 /**
8731 * Get a readable String for a bitmask of declared methods.
8732 */
8733 @VisibleForTesting
8734 public static String declaredMethodsFlagsToString(int flags) {
8735 if (flags == DECLARED_METHODS_NONE) {
8736 return "NONE";
8737 }
8738 if (flags == DECLARED_METHODS_ALL) {
8739 return "ALL";
8740 }
8741 final StringBuilder sb = new StringBuilder();
8742 flags = maybeAppendDeclaredMethod(flags, CALLBACK_PRECHECK, "PRECHK", sb);
8743 flags = maybeAppendDeclaredMethod(flags, CALLBACK_AVAILABLE, "AVAIL", sb);
8744 flags = maybeAppendDeclaredMethod(flags, CALLBACK_LOSING, "LOSING", sb);
8745 flags = maybeAppendDeclaredMethod(flags, CALLBACK_LOST, "LOST", sb);
8746 flags = maybeAppendDeclaredMethod(flags, CALLBACK_UNAVAIL, "UNAVAIL", sb);
8747 flags = maybeAppendDeclaredMethod(flags, CALLBACK_CAP_CHANGED, "NC", sb);
8748 flags = maybeAppendDeclaredMethod(flags, CALLBACK_IP_CHANGED, "LP", sb);
8749 flags = maybeAppendDeclaredMethod(flags, CALLBACK_SUSPENDED, "SUSP", sb);
8750 flags = maybeAppendDeclaredMethod(flags, CALLBACK_RESUMED, "RESUME", sb);
8751 flags = maybeAppendDeclaredMethod(flags, CALLBACK_BLK_CHANGED, "BLK", sb);
8752 flags = maybeAppendDeclaredMethod(flags, CALLBACK_LOCAL_NETWORK_INFO_CHANGED,
8753 "LOCALINF", sb);
Patrick Rohr93136f12024-12-02 15:46:48 -08008754 flags = maybeAppendDeclaredMethod(flags, CALLBACK_RESERVED, "RES", sb);
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +09008755 if (flags != 0) {
8756 sb.append("|0x").append(Integer.toHexString(flags));
8757 }
8758 return sb.toString();
8759 }
8760
8761 private static int maybeAppendDeclaredMethod(int declaredMethodsFlags,
8762 int callbackId, String callbackName, @NonNull StringBuilder builder) {
8763 final int callbackFlag = 1 << callbackId;
8764 if ((declaredMethodsFlags & callbackFlag) != 0) {
8765 if (builder.length() > 0) {
8766 builder.append('|');
8767 }
8768 builder.append(callbackName);
8769 }
8770 return declaredMethodsFlags & ~callbackFlag;
8771 }
8772
Junyu Lai00d92df2022-07-05 11:01:52 +08008773 // Keep backward compatibility since the ServiceSpecificException is used by
8774 // the API surface, see {@link ConnectivityManager#convertServiceException}.
8775 public static class RequestInfoPerUidCounter extends PerUidCounter {
8776 RequestInfoPerUidCounter(int maxCountPerUid) {
8777 super(maxCountPerUid);
8778 }
8779
8780 @Override
8781 public synchronized void incrementCountOrThrow(int uid) {
8782 try {
8783 super.incrementCountOrThrow(uid);
8784 } catch (IllegalStateException e) {
8785 throw new ServiceSpecificException(
8786 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
8787 "Uid " + uid + " exceeded its allotted requests limit");
8788 }
8789 }
8790
8791 @Override
8792 public synchronized void decrementCountOrThrow(int uid) {
8793 throw new UnsupportedOperationException("Use decrementCount instead.");
8794 }
8795
8796 public synchronized void decrementCount(int uid) {
8797 try {
8798 super.decrementCountOrThrow(uid);
8799 } catch (IllegalStateException e) {
8800 logwtf("Exception when decrement per uid request count: ", e);
8801 }
8802 }
8803 }
8804
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008805 // This checks that the passed capabilities either do not request a
8806 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008807 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008808 int callerPid, int callerUid, String callerPackageName) {
Junyu Lai71b51532024-02-01 10:39:01 +08008809 if (null != nc.getSsid() && !hasSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008810 throw new SecurityException("Insufficient permissions to request a specific SSID");
8811 }
paulhu1a407652019-03-22 16:35:06 +08008812
8813 if (nc.hasSignalStrength()
Junyu Lai71b51532024-02-01 10:39:01 +08008814 && !hasNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
paulhu1a407652019-03-22 16:35:06 +08008815 throw new SecurityException(
8816 "Insufficient permissions to request a specific signal strength");
8817 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08008818 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008819 }
8820
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008821 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008822 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008823 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08008824 // mNetworkRequests may contain the same value multiple times in case of
8825 // multilayer requests. It won't matter in this case because the thresholds
8826 // will then be the same and be deduplicated as they enter the `thresholds` set.
8827 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08008828 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8829 for (final NetworkRequest req : nri.mRequests) {
8830 if (req.networkCapabilities.hasSignalStrength()
8831 && nai.satisfiesImmutableCapabilitiesOf(req)) {
8832 thresholds.add(req.networkCapabilities.getSignalStrength());
8833 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008834 }
8835 }
8836 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008837 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008838 }
8839
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008840 private void updateSignalStrengthThresholds(
8841 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008842 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008843
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09008844 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008845 String detail;
8846 if (request != null && request.networkCapabilities.hasSignalStrength()) {
8847 detail = reason + " " + request.networkCapabilities.getSignalStrength();
8848 } else {
8849 detail = reason;
8850 }
8851 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008852 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008853 }
8854
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008855 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008856 }
8857
Chalard Jeandd421992021-12-16 23:16:02 +09008858 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07008859 if (nc == null) {
8860 return;
8861 }
8862 NetworkSpecifier ns = nc.getNetworkSpecifier();
8863 if (ns == null) {
8864 return;
8865 }
lucaslin22f9b9f2021-01-22 15:15:23 +08008866 if (ns instanceof MatchAllNetworkSpecifier) {
8867 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
8868 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07008869 }
8870
Chalard Jeandd421992021-12-16 23:16:02 +09008871 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08008872 ensureValidNetworkSpecifier(nc);
8873 if (nc.isPrivateDnsBroken()) {
8874 throw new IllegalArgumentException("Can't request broken private DNS");
8875 }
Chalard Jeande665262022-02-25 16:12:12 +09008876 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09008877 throw new IllegalArgumentException("Can't request access UIDs");
8878 }
lucasline117e2e2019-10-22 18:27:33 +08008879 }
8880
Chalard Jeandd421992021-12-16 23:16:02 +09008881 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
8882 ensureListenableCapabilities(nc);
8883 final String badCapability = nc.describeFirstNonRequestableCapability();
8884 if (badCapability != null) {
8885 throw new IllegalArgumentException("Cannot request network with " + badCapability);
8886 }
8887 }
8888
Chiachang Wang3bc52762021-11-25 14:17:57 +08008889 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
8890 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08008891 private boolean isTargetSdkAtleast(int version, int callingUid,
8892 @NonNull String callingPackageName) {
8893 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08008894 final PackageManager pm =
8895 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08008896 try {
Roshan Pius951c0032020-12-22 15:10:42 -08008897 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08008898 if (callingVersion < version) return false;
8899 } catch (PackageManager.NameNotFoundException e) { }
8900 return true;
8901 }
8902
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008903 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09008904 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09008905 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08008906 int legacyType, int callbackFlags, @NonNull String callingPackageName,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09008907 @Nullable String callingAttributionTag, int declaredMethodsFlag) {
8908 if (declaredMethodsFlag == 0) {
8909 // This could happen if raw binder calls are used to call the previous overload of
8910 // requestNetwork, as missing int arguments in a binder call end up as 0
8911 // (Parcel.readInt returns 0 at the end of a parcel). Such raw calls this would be
8912 // really unexpected bad behavior from the caller though.
8913 // TODO: remove after verifying this does not happen. This could allow enabling the
8914 // optimization for callbacks that do not override any method (right now they use
8915 // DECLARED_METHODS_ALL), if it is OK to break NetworkCallbacks created using
8916 // dexmaker-mockito-inline and either spy() or MockSettings.useConstructor (see
8917 // comment in ConnectivityManager which sets the flag to DECLARED_METHODS_ALL).
8918 Log.wtf(TAG, "requestNetwork called without declaredMethodsFlag from "
8919 + callingPackageName);
8920 declaredMethodsFlag = DECLARED_METHODS_ALL;
8921 }
Junyu Lai71b51532024-02-01 10:39:01 +08008922 if (legacyType != TYPE_NONE && !hasNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08008923 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
8924 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08008925 throw new SecurityException("Insufficient permissions to specify legacy type");
8926 }
markchienfac84a22020-03-18 21:16:15 +08008927 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09008928 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008929 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09008930 // Privileged callers can track the default network of another UID by passing in a UID.
8931 if (asUid != Process.INVALID_UID) {
8932 enforceSettingsPermission();
8933 } else {
8934 asUid = callingUid;
8935 }
junyulaiad010792021-01-11 16:53:38 +08008936 final NetworkRequest.Type reqType;
8937 try {
8938 reqType = NetworkRequest.Type.values()[reqTypeInt];
8939 } catch (ArrayIndexOutOfBoundsException e) {
8940 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
8941 }
8942 switch (reqType) {
8943 case TRACK_DEFAULT:
8944 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09008945 // is unused and will be replaced by ones appropriate for the UID (usually, the
8946 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008947 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09008948 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08008949 enforceAccessPermission();
8950 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09008951 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00008952 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09008953 networkCapabilities = new NetworkCapabilities(defaultNc);
8954 break;
Junyu Laia62493f2021-01-19 11:10:56 +00008955 case BACKGROUND_REQUEST:
8956 enforceNetworkStackOrSettingsPermission();
8957 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08008958 case REQUEST:
Patrick Rohre4c602e2024-11-26 12:15:17 -08008959 case RESERVATION:
junyulaiad010792021-01-11 16:53:38 +08008960 networkCapabilities = new NetworkCapabilities(networkCapabilities);
8961 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08008962 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08008963 // TODO: this is incorrect. We mark the request as metered or not depending on
8964 // the state of the app when the request is filed, but we never change the
8965 // request if the app changes network state. http://b/29964605
8966 enforceMeteredApnPolicy(networkCapabilities);
Motomu Utsumiad480e02024-01-30 16:21:51 +09008967 maybeDisableLocalNetworkMatching(networkCapabilities, callingUid);
junyulaiad010792021-01-11 16:53:38 +08008968 break;
junyulai1b1c8742021-03-12 20:05:08 +08008969 case LISTEN_FOR_BEST:
8970 enforceAccessPermission();
8971 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Motomu Utsumiad480e02024-01-30 16:21:51 +09008972 maybeDisableLocalNetworkMatching(networkCapabilities, callingUid);
junyulai1b1c8742021-03-12 20:05:08 +08008973 break;
junyulaiad010792021-01-11 16:53:38 +08008974 default:
8975 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09008976 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09008977 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008978 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008979 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09008980
junyulai1b1c8742021-03-12 20:05:08 +08008981 // Enforce FOREGROUND if the caller does not have permission to use background network.
8982 if (reqType == LISTEN_FOR_BEST) {
8983 restrictBackgroundRequestForCaller(networkCapabilities);
8984 }
8985
8986 // Set the UID range for this request to the single UID of the requester, unless the
8987 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09008988 // This will overwrite any allowed UIDs in the requested capabilities. Though there
8989 // are no visible methods to set the UIDs, an app could use reflection to try and get
8990 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08008991 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08008992 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
8993 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07008994
Etan Cohen85000162017-02-05 10:42:27 -08008995 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008996 throw new IllegalArgumentException("Bad timeout specified");
8997 }
Etan Cohen9786d922015-11-18 10:56:15 -08008998
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09008999 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
9000 // copied from the default request above. (This is necessary to ensure, for example, that
9001 // the callback does not leak sensitive information to unprivileged apps.) Check that the
9002 // changes don't alter request matching.
9003 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
9004 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09009005 throw new IllegalStateException(
9006 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09009007 + networkCapabilities + " vs. " + defaultNc);
9008 }
9009
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009010 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
9011 nextNetworkRequestId(), reqType);
9012 final NetworkRequestInfo nri = getNriToRegister(
9013 asUid, networkRequest, messenger, binder, callbackFlags,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09009014 callingAttributionTag, declaredMethodsFlag);
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009015 if (DBG) log("requestNetwork for " + nri);
9016 trackUidAndRegisterNetworkRequest(EVENT_REGISTER_NETWORK_REQUEST, nri);
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07009017 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009018 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07009019 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009020 }
9021 return networkRequest;
9022 }
9023
James Mattis3ce3d3c2021-02-09 18:18:28 -08009024 /**
9025 * Return the nri to be used when registering a network request. Specifically, this is used with
9026 * requests registered to track the default request. If there is currently a per-app default
9027 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
9028 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009029 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
9030 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009031 * @param nr the network request for the nri.
9032 * @param msgr the messenger for the nri.
9033 * @param binder the binder for the nri.
9034 * @param callingAttributionTag the calling attribution tag for the nri.
9035 * @return the nri to register.
9036 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009037 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08009038 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08009039 @NetworkCallback.Flag int callbackFlags,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09009040 @Nullable String callingAttributionTag, int declaredMethodsFlags) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08009041 final List<NetworkRequest> requests;
9042 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
9043 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009044 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08009045 } else {
9046 requests = Collections.singletonList(nr);
9047 }
Roshan Pius951c0032020-12-22 15:10:42 -08009048 return new NetworkRequestInfo(
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09009049 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag,
9050 declaredMethodsFlags);
James Mattis3ce3d3c2021-02-09 18:18:28 -08009051 }
9052
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09009053 private boolean shouldCheckCapabilitiesDeclaration(
9054 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
9055 @NonNull final String callingPackageName) {
9056 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
9057 // Only run the check if the change is enabled.
9058 if (!mDeps.isChangeEnabled(
Motomu Utsumiad480e02024-01-30 16:21:51 +09009059 ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09009060 callingPackageName, user)) {
9061 return false;
9062 }
9063
9064 return networkCapabilities.hasCapability(
9065 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
9066 || networkCapabilities.hasCapability(
9067 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
9068 }
9069
9070 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09009071 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09009072 // This check is added to fix the linter error for "current min is 30", which is not going
9073 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09009074 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09009075 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
9076 return;
9077 }
9078 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09009079 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09009080 try {
9081 synchronized (mSelfCertifiedCapabilityCache) {
9082 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
9083 callerPackageName);
9084 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09009085 final PackageManager packageManager =
9086 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
9087 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09009088 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
9089 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
9090 callerPackageName
9091 );
9092 final XmlResourceParser parser = packageManager
9093 .getResourcesForApplication(callerPackageName)
9094 .getXml(networkSliceProperty.getResourceId());
9095 applicationNetworkCapabilities =
9096 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
9097 mSelfCertifiedCapabilityCache.put(callerPackageName,
9098 applicationNetworkCapabilities);
9099 }
9100
9101 }
9102 } catch (PackageManager.NameNotFoundException ne) {
9103 throw new SecurityException(
9104 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
9105 + " property");
9106 } catch (XmlPullParserException | IOException | InvalidTagException e) {
9107 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09009108 } finally {
9109 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09009110 }
9111
9112 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
9113 networkCapabilities);
9114 }
Ying Xu7cabd322024-01-15 18:40:15 -08009115
9116 private boolean canRequestRestrictedNetworkDueToCarrierPrivileges(
9117 NetworkCapabilities networkCapabilities, int callingUid) {
9118 if (mRequestRestrictedWifiEnabled) {
9119 // For U+ devices, callers with carrier privilege could request restricted networks
9120 // with CBS capabilities, or any restricted WiFi networks.
9121 return ((networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
9122 || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))
9123 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities));
9124 } else {
9125 // For T+ devices, callers with carrier privilege could request with CBS
9126 // capabilities.
9127 return (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
9128 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities));
9129 }
9130 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07009131 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08009132 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09009133 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
9134 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09009135 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
9136 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09009137 }
Ying Xu7cabd322024-01-15 18:40:15 -08009138 if (!networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9139 if (!canRequestRestrictedNetworkDueToCarrierPrivileges(
9140 networkCapabilities, callingUid)) {
9141 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08009142 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009143 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07009144 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009145 }
9146 }
9147
fenglu3f357402015-03-20 11:29:56 -07009148 @Override
fenglub00f4882015-04-21 17:12:05 -07009149 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07009150 enforceAccessPermission();
9151 NetworkAgentInfo nai = null;
9152 if (network == null) {
9153 return false;
9154 }
9155 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08009156 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07009157 }
9158 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009159 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07009160 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009161 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07009162 Integer uidReqs = mBandwidthRequests.get(uid);
9163 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009164 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07009165 }
9166 mBandwidthRequests.put(uid, ++uidReqs);
9167 }
fenglu3f357402015-03-20 11:29:56 -07009168 return true;
9169 }
9170 return false;
9171 }
9172
Felipe Leme0a5ae422016-06-20 16:36:29 -07009173 private boolean isSystem(int uid) {
9174 return uid < Process.FIRST_APPLICATION_UID;
9175 }
fenglu3f357402015-03-20 11:29:56 -07009176
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009177 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009178 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07009179 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09009180 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07009181 return;
9182 }
Hugo Benichi39621362017-02-11 17:04:43 +09009183 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
9184 // Policy already enforced.
9185 return;
9186 }
Motomu Utsumie9c07ff2024-06-26 13:10:23 +09009187 final boolean isRestrictedOnMeteredNetworks = mDeps.isAtLeastV()
9188 ? mBpfNetMaps.isUidRestrictedOnMeteredNetworks(uid)
9189 : BinderUtils.withCleanCallingIdentity(() ->
9190 mPolicyManager.isUidRestrictedOnMeteredNetworks(uid));
9191 if (isRestrictedOnMeteredNetworks) {
9192 // If UID is restricted, don't allow them to bring up metered APNs.
9193 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009194 }
9195 }
9196
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009197 @Override
9198 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07009199 PendingIntent operation, @NonNull String callingPackageName,
9200 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00009201 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009202 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009203 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07009204 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08009205 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009206 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09009207 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09009208 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08009209 Binder.getCallingPid(), callingUid, callingPackageName);
Motomu Utsumiad480e02024-01-30 16:21:51 +09009210 restrictRequestNetworkCapabilitiesForCaller(
9211 networkCapabilities, callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09009212
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009213 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09009214 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009215 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
9216 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09009217 if (DBG) log("pendingRequest for " + nri);
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009218 trackUidAndRegisterNetworkRequest(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT, nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009219 return networkRequest;
9220 }
9221
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009222 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
9223 mHandler.sendMessageDelayed(
9224 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009225 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009226 }
9227
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009228 @Override
9229 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00009230 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009231 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009232 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009233 }
9234
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09009235 // In order to implement the compatibility measure for pre-M apps that call
9236 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
9237 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
9238 // This ensures it has permission to do so.
9239 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
9240 if (nc == null) {
9241 return false;
9242 }
9243 int[] transportTypes = nc.getTransportTypes();
9244 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
9245 return false;
9246 }
9247 try {
9248 mContext.enforceCallingOrSelfPermission(
9249 android.Manifest.permission.ACCESS_WIFI_STATE,
9250 "ConnectivityService");
9251 } catch (SecurityException e) {
9252 return false;
9253 }
9254 return true;
9255 }
9256
Motomu Utsumid20727f2024-05-23 21:44:40 +09009257 private boolean isAppRequest(NetworkRequestInfo nri) {
9258 return nri.mMessenger != null || nri.mPendingIntent != null;
9259 }
9260
9261 private void trackUidAndMaybePostCurrentBlockedReason(final NetworkRequestInfo nri) {
9262 if (!isAppRequest(nri)) {
9263 Log.wtf(TAG, "trackUidAndMaybePostCurrentBlockedReason is called for non app"
9264 + "request: " + nri);
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009265 return;
9266 }
9267 nri.mPerUidCounter.incrementCountOrThrow(nri.mUid);
Motomu Utsumid20727f2024-05-23 21:44:40 +09009268
9269 // If nri.mMessenger is null, this nri does not have NetworkCallback so ConnectivityService
9270 // does not need to send onBlockedStatusChanged callback for this uid and does not need to
9271 // track the uid in mBlockedStatusTrackingUids
9272 if (!shouldTrackUidsForBlockedStatusCallbacks() || nri.mMessenger == null) {
9273 return;
9274 }
9275 if (nri.mUidTrackedForBlockedStatus) {
9276 Log.wtf(TAG, "Nri is already tracked for sending blocked status: " + nri);
9277 return;
9278 }
9279 nri.mUidTrackedForBlockedStatus = true;
9280 synchronized (mBlockedStatusTrackingUids) {
9281 final int uid = nri.mAsUid;
9282 final int count = mBlockedStatusTrackingUids.get(uid, 0);
9283 if (count == 0) {
9284 mHandler.sendMessage(mHandler.obtainMessage(EVENT_BLOCKED_REASONS_CHANGED,
9285 List.of(new Pair<>(uid, mBpfNetMaps.getUidNetworkingBlockedReasons(uid)))));
9286 }
9287 mBlockedStatusTrackingUids.put(uid, count + 1);
9288 }
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009289 }
9290
9291 private void trackUidAndRegisterNetworkRequest(final int event, NetworkRequestInfo nri) {
Motomu Utsumid20727f2024-05-23 21:44:40 +09009292 // Post the update of the UID's blocked reasons before posting the message that registers
9293 // the callback. This is necessary because if the callback immediately matches a request,
9294 // the onBlockedStatusChanged must be called with the correct blocked reasons.
9295 // Also, once trackUidAndMaybePostCurrentBlockedReason is called, the register network
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009296 // request event must be posted, because otherwise the counter for uid will never be
9297 // decremented.
Motomu Utsumid20727f2024-05-23 21:44:40 +09009298 trackUidAndMaybePostCurrentBlockedReason(nri);
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009299 mHandler.sendMessage(mHandler.obtainMessage(event, nri));
9300 }
9301
Motomu Utsumid20727f2024-05-23 21:44:40 +09009302 private void maybeUntrackUidAndClearBlockedReasons(final NetworkRequestInfo nri) {
9303 if (!isAppRequest(nri)) {
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009304 // Not an app request.
9305 return;
9306 }
9307 nri.mPerUidCounter.decrementCount(nri.mUid);
Motomu Utsumid20727f2024-05-23 21:44:40 +09009308
9309 if (!shouldTrackUidsForBlockedStatusCallbacks() || nri.mMessenger == null) {
9310 return;
9311 }
9312 if (!nri.mUidTrackedForBlockedStatus) {
9313 Log.wtf(TAG, "Nri is not tracked for sending blocked status: " + nri);
9314 return;
9315 }
9316 nri.mUidTrackedForBlockedStatus = false;
9317 synchronized (mBlockedStatusTrackingUids) {
9318 final int count = mBlockedStatusTrackingUids.get(nri.mAsUid);
9319 if (count > 1) {
9320 mBlockedStatusTrackingUids.put(nri.mAsUid, count - 1);
9321 } else {
9322 mBlockedStatusTrackingUids.delete(nri.mAsUid);
9323 mUidBlockedReasons.delete(nri.mAsUid);
9324 }
9325 }
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009326 }
9327
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009328 @Override
9329 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08009330 Messenger messenger, IBinder binder,
9331 @NetworkCallback.Flag int callbackFlags,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09009332 @NonNull String callingPackageName, @NonNull String callingAttributionTag,
9333 int declaredMethodsFlag) {
9334 if (declaredMethodsFlag == 0) {
9335 Log.wtf(TAG, "listenForNetwork called without declaredMethodsFlag from "
9336 + callingPackageName);
9337 declaredMethodsFlag = DECLARED_METHODS_ALL;
9338 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009339 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09009340 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
9341 enforceAccessPermission();
9342 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009343
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09009344 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09009345 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08009346 Binder.getCallingPid(), callingUid, callingPackageName);
Motomu Utsumiad480e02024-01-30 16:21:51 +09009347 restrictRequestNetworkCapabilitiesForCaller(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09009348 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
9349 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
9350 // onLost and onAvailable callbacks when networks move in and out of the background.
9351 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
9352 // can't request networks.
9353 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09009354 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07009355
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09009356 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09009357 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08009358 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009359 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +09009360 callingAttributionTag, declaredMethodsFlag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09009361 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009362
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009363 trackUidAndRegisterNetworkRequest(EVENT_REGISTER_NETWORK_LISTENER, nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009364 return networkRequest;
9365 }
9366
9367 @Override
9368 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08009369 PendingIntent operation, @NonNull String callingPackageName,
9370 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00009371 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009372 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04009373 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
9374 enforceAccessPermission();
9375 }
Chalard Jeandd421992021-12-16 23:16:02 +09009376 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09009377 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08009378 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09009379 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Motomu Utsumiad480e02024-01-30 16:21:51 +09009380 restrictRequestNetworkCapabilitiesForCaller(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09009381
9382 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09009383 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009384 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
9385 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09009386 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04009387
Motomu Utsumib16f75c2024-05-23 19:25:17 +09009388 trackUidAndRegisterNetworkRequest(EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009389 }
9390
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09009391 /** Returns the next Network provider ID. */
9392 public final int nextNetworkProviderId() {
9393 return mNextNetworkProviderId.getAndIncrement();
9394 }
9395
Erik Kline0c04b742016-07-07 16:50:58 +09009396 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009397 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Patrick Rohr8b42a112024-12-23 14:00:07 -08009398 ensureNetworkRequestHasSupportedType(networkRequest, false /* isMultilayerRequest */);
Erik Kline0c04b742016-07-07 16:50:58 +09009399 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009400 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009401 }
9402
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009403 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
9404 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09009405 // Avoid creating duplicates. even if an app makes a direct AIDL call.
9406 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
9407 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08009408 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009409 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09009410 return;
9411 }
9412
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009413 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
9414 mNetworkProviderInfos.put(npi.messenger, npi);
9415 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09009416 }
9417
9418 @Override
9419 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08009420 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009421 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009422 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08009423 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009424 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
9425 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09009426 }
9427
9428 @Override
9429 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08009430 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009431 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07009432 }
9433
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009434 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09009435 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009436 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
9437 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09009438 Objects.requireNonNull(score);
9439 Objects.requireNonNull(caps);
9440 Objects.requireNonNull(callback);
Patrick Rohrff652572024-12-20 09:52:33 -08009441 if (caps.hasTransport(TRANSPORT_TEST)) {
9442 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
9443 } else {
9444 enforceNetworkFactoryPermission();
9445 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09009446 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009447 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09009448 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
9449 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009450 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
9451 }
9452
Chalard Jeanbb902a52021-08-18 01:35:19 +09009453 private void updateOfferScore(final NetworkOffer offer) {
9454 final boolean yieldToBadWiFi =
9455 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
9456 final NetworkOffer newOffer = new NetworkOffer(
9457 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
9458 offer.caps, offer.callback, offer.providerId);
9459 if (offer.equals(newOffer)) return;
9460 handleRegisterNetworkOffer(newOffer);
9461 }
9462
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009463 @Override
9464 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08009465 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009466 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
9467 }
9468
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009469 private void handleUnregisterNetworkProvider(Messenger messenger) {
9470 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
9471 if (npi == null) {
9472 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07009473 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009474 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009475 // Unregister all the offers from this provider
9476 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
9477 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09009478 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009479 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
9480 toRemove.add(noi);
9481 }
9482 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09009483 for (final NetworkOfferInfo noi : toRemove) {
Patrick Rohre7a4b082024-12-17 19:02:11 -08009484 handleUnregisterNetworkOffer(noi, true /* releaseReservations */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009485 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009486 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07009487 }
9488
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09009489 @Override
James Mattisf7027322020-12-13 16:28:14 -08009490 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08009491 if (request.hasTransport(TRANSPORT_TEST)) {
9492 enforceNetworkFactoryOrTestNetworksPermission();
9493 } else {
9494 enforceNetworkFactoryPermission();
9495 }
James Mattisf7027322020-12-13 16:28:14 -08009496 final NetworkRequestInfo nri = mNetworkRequests.get(request);
9497 if (nri != null) {
9498 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
9499 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
9500 mHandler.post(() -> handleReleaseNetworkRequest(
9501 nri.mRequests.get(0), mDeps.getCallingUid(), true));
9502 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09009503 }
9504
Paul Jensen1f567382015-02-13 14:18:39 -05009505 // NOTE: Accessed on multiple threads, must be synchronized on itself.
9506 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09009507 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05009508 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09009509 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05009510 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09009511 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009512
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009513 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05009514 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean2f52a0e2025-03-21 10:14:28 +09009515 // Code iterating over this set is recommended to use forAllNetworkAgentInfos(), which allows
9516 // code within the loop to disconnect networks during iteration without causing null pointer or
9517 // OOB exceptions.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009518 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009519
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009520 // UID ranges for users that are currently blocked by VPNs.
9521 // This array is accessed and iterated on multiple threads without holding locks, so its
9522 // contents must never be mutated. When the ranges change, the array is replaced with a new one
9523 // (on the handler thread).
9524 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
9525
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009526 // Must only be accessed on the handler thread
9527 @NonNull
9528 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
9529
Lorenzo Colittiac136a02016-01-22 04:04:57 +09009530 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09009531 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09009532
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009533 // Current OEM network preferences. This object must only be written to on the handler thread.
9534 // Since it is immutable and always non-null, other threads may read it if they only care
9535 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08009536 @NonNull
9537 private OemNetworkPreferences mOemNetworkPreferences =
9538 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09009539 // Current per-profile network preferences. This object follows the same threading rules as
9540 // the OEM network preferences above.
9541 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09009542 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
9543 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08009544
lucaslin3ba7cc22022-12-19 02:35:33 +00009545 // Current VPN network preferences. This object follows the same threading rules as the OEM
9546 // network preferences above.
9547 @NonNull
9548 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
9549 mVpnNetworkPreferences = new NetworkPreferenceList<>();
9550
paulhu51f77dc2021-06-07 02:34:20 +00009551 // A set of UIDs that should use mobile data preferentially if available. This object follows
9552 // the same threading rules as the OEM network preferences above.
9553 @NonNull
9554 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
9555
James Mattiscb1e0362021-04-06 17:07:42 -07009556 // OemNetworkPreferences activity String log entries.
9557 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
9558 @NonNull
9559 private final LocalLog mOemNetworkPreferencesLogs =
9560 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
9561
James Mattis02220e22021-03-13 19:27:21 -08009562 /**
9563 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
9564 * @param packageName the package name to check existence of a mapping for.
9565 * @return true if a mapping exists, false otherwise
9566 */
9567 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
9568 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
9569 }
9570
James Mattise3ef1912020-12-20 11:09:58 -08009571 // The always-on request for an Internet-capable network that apps without a specific default
9572 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08009573 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09009574 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08009575 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08009576 // Collection of NetworkRequestInfo's used for default networks.
Motomu Utsumi7b906de2024-08-30 19:44:54 +09009577 // This set is read and iterated on multiple threads.
9578 // Using CopyOnWriteArraySet since number of default network request is small (system default
9579 // network request + per-app default network requests) and updated infrequently but read
9580 // frequently.
James Mattis45d81842021-01-10 14:24:24 -08009581 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08009582 @NonNull
Motomu Utsumi7b906de2024-08-30 19:44:54 +09009583 final CopyOnWriteArraySet<NetworkRequestInfo> mDefaultNetworkRequests =
9584 new CopyOnWriteArraySet<>();
9585
Chalard Jeand4f01ca2018-05-18 22:02:56 +09009586
James Mattisd31bdfa2020-12-23 16:37:26 -08009587 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
9588 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
9589 }
9590
9591 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08009592 * Return the default network request currently tracking the given uid.
9593 * @param uid the uid to check.
9594 * @return the NetworkRequestInfo tracking the given uid.
9595 */
9596 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08009597 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08009598 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08009599 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08009600 // Checking the first request is sufficient as only multilayer requests will have more
9601 // than one request and for multilayer, all requests will track the same uids.
9602 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08009603 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08009604 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08009605 highestPriorityNri = nri;
9606 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08009607 }
9608 }
paulhuaa0743d2021-05-26 21:56:03 +08009609 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08009610 }
9611
9612 /**
9613 * Get a copy of the network requests of the default request that is currently tracking the
9614 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009615 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
9616 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009617 * @param requestorUid the uid to check the default for.
9618 * @param requestorPackageName the requestor's package name.
9619 * @return a copy of the default's NetworkRequest that is tracking the given uid.
9620 */
9621 @NonNull
9622 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009623 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08009624 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009625 getDefaultRequestTrackingUid(asUid).mRequests,
9626 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08009627 }
9628
9629 /**
9630 * Copy the given nri's NetworkRequest collection.
9631 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009632 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
9633 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009634 * @param requestorUid the uid to set on the copied collection.
9635 * @param requestorPackageName the package name to set on the copied collection.
9636 * @return the copied NetworkRequest collection.
9637 */
9638 @NonNull
9639 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009640 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
9641 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08009642 final List<NetworkRequest> requests = new ArrayList<>();
9643 for (final NetworkRequest nr : requestsToCopy) {
9644 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009645 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08009646 nr.legacyType, nextNetworkRequestId(), nr.type));
9647 }
9648 return requests;
9649 }
9650
9651 @NonNull
9652 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009653 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
9654 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09009655 // These capabilities are for a TRACK_DEFAULT callback, so:
9656 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
9657 // mDefaultRequest and a per-UID default request.
9658 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009659 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09009660 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009661 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
9662 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009663 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08009664 restrictRequestUidsForCallerAndSetRequestorInfo(
9665 netCap, requestorUid, requestorPackageName);
9666 return netCap;
9667 }
9668
9669 /**
9670 * Get the nri that is currently being tracked for callbacks by per-app defaults.
9671 * @param nr the network request to check for equality against.
9672 * @return the nri if one exists, null otherwise.
9673 */
9674 @Nullable
9675 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
9676 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9677 if (nri.getNetworkRequestForCallback().equals(nr)) {
9678 return nri;
9679 }
9680 }
9681 return null;
9682 }
9683
9684 /**
9685 * Check if an nri is currently being managed by per-app default networking.
9686 * @param nri the nri to check.
9687 * @return true if this nri is currently being managed by per-app default networking.
9688 */
9689 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
9690 // nri.mRequests.get(0) is only different from the original request filed in
9691 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
9692 // functionality therefore if these two don't match, it means this particular nri is
9693 // currently being managed by a per-app default.
9694 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
9695 }
9696
9697 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08009698 * Determine if an nri is a managed default request that disallows default networking.
9699 * @param nri the request to evaluate
9700 * @return true if device-default networking is disallowed
9701 */
9702 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
9703 // Check if this nri is a managed default that supports the default network at its
9704 // lowest priority request.
9705 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
9706 final NetworkCapabilities lowestPriorityNetCap =
9707 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
9708 return isPerAppDefaultRequest(nri)
9709 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
9710 lowestPriorityNetCap));
9711 }
9712
Erik Kline05f2b402015-04-30 12:58:40 +09009713 // Request used to optionally keep mobile data active even when higher
9714 // priority networks like Wi-Fi are active.
9715 private final NetworkRequest mDefaultMobileDataRequest;
9716
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07009717 // Request used to optionally keep wifi data active even when higher
9718 // priority networks like ethernet are active.
9719 private final NetworkRequest mDefaultWifiRequest;
9720
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08009721 // Request used to optionally keep vehicle internal network always active
9722 private final NetworkRequest mDefaultVehicleRequest;
9723
James Mattisd31bdfa2020-12-23 16:37:26 -08009724 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
9725 // network with no service. This NAI should never be matched against, nor should any public API
9726 // ever return the associated network. For this reason, this NAI is not in the list of available
9727 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
9728 // default requests that don't support using the device default network which will ultimately
9729 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
9730 @VisibleForTesting
9731 final NetworkAgentInfo mNoServiceNetwork;
9732
Chalard Jean5b409c72021-02-04 13:12:59 +09009733 // The NetworkAgentInfo currently satisfying the default request, if any.
9734 private NetworkAgentInfo getDefaultNetwork() {
9735 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09009736 }
9737
James Mattis2516da32021-01-31 17:06:19 -08009738 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08009739 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08009740 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9741 // Currently, all network requests will have the same uids therefore checking the first
9742 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009743 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08009744 if (null == uids) {
9745 continue;
9746 }
9747 for (final UidRange range : uids) {
9748 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08009749 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08009750 highestPriorityNri = nri;
9751 }
James Mattis2516da32021-01-31 17:06:19 -08009752 }
9753 }
9754 }
Hansen Kurlied972a62023-09-07 16:26:02 +08009755 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08009756 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08009757 }
9758
Varun Ananddf569952019-02-06 10:13:38 -08009759 @Nullable
9760 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
9761 return nai != null ? nai.network : null;
9762 }
9763
9764 private void ensureRunningOnConnectivityServiceThread() {
Paul Huc0e70972024-10-04 06:22:24 +00009765 HandlerUtils.ensureRunningOnHandlerThread(mHandler);
Varun Ananddf569952019-02-06 10:13:38 -08009766 }
9767
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009768 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09009769 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
9770 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07009771 }
9772
Chalard Jean29d06db2018-05-02 21:14:54 +09009773 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09009774 * Returns whether local agents are supported on this device.
9775 *
9776 * Local agents are supported from U on TVs, and from V on all devices.
9777 */
9778 @VisibleForTesting
9779 public boolean areLocalAgentsSupported() {
9780 final PackageManager pm = mContext.getPackageManager();
9781 // Local agents are supported starting on U on TVs and on V on everything else.
9782 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
9783 }
9784
9785 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09009786 * Register a new agent with ConnectivityService to handle a network.
9787 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009788 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09009789 * @param networkInfo the initial info associated with this network. It can be updated later :
9790 * see {@link #updateNetworkInfo}.
9791 * @param linkProperties the initial link properties of this network. They can be updated
9792 * later : see {@link #updateLinkProperties}.
9793 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09009794 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009795 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009796 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009797 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009798 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09009799 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09009800 */
Chalard Jean8a976922025-03-18 09:27:33 +09009801 public NetworkAndAgentRegistryParcelable registerNetworkAgent(INetworkAgent na,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009802 NetworkInfo networkInfo,
9803 LinkProperties linkProperties,
9804 NetworkCapabilities networkCapabilities,
9805 @NonNull NetworkScore initialScore,
9806 @Nullable LocalNetworkConfig localNetworkConfig,
9807 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09009808 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09009809 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
9810 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
9811 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09009812 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09009813 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09009814 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08009815 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09009816 } else {
9817 enforceNetworkFactoryPermission();
9818 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009819 final boolean hasLocalCap =
9820 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
9821 if (hasLocalCap && !areLocalAgentsSupported()) {
9822 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
9823 throw new IllegalArgumentException("Local agents are not supported in this version");
9824 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009825 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
9826 if (hasLocalCap != hasLocalNetworkConfig) {
9827 throw new IllegalArgumentException(null != localNetworkConfig
9828 ? "Only local network agents can have a LocalNetworkConfig"
9829 : "Local network agents must have a LocalNetworkConfig"
9830 );
9831 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09009832
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009833 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09009834 final long token = Binder.clearCallingIdentity();
9835 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009836 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009837 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
9838 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09009839 } finally {
9840 Binder.restoreCallingIdentity(token);
9841 }
9842 }
9843
Chalard Jean8a976922025-03-18 09:27:33 +09009844 private NetworkAndAgentRegistryParcelable registerNetworkAgentInternal(
9845 INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09009846 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009847 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
9848 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09009849 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009850
Chalard Jeandbc46952022-02-02 00:14:18 +09009851 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
9852 // and mutate them at any time.
9853 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
9854 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
9855 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009856 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09009857
Chalard Jean366c5252022-01-25 18:27:53 +09009858 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09009859 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09009860 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
9861 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009862 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09009863 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009864 localNetworkConfig, currentScore, mContext, mTrackerHandler,
9865 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
9866 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009867
Chalard Jeandbc46952022-02-02 00:14:18 +09009868 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09009869 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09009870 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009871 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09009872 mDeps.getNetworkStack().makeNetworkMonitor(
9873 nai.network, name, new NetworkMonitorCallbacks(nai));
Chalard Jean391ec5d2025-03-07 10:54:52 +09009874 // NetworkAgentInfo registration is done, but CS will only accept messages when the
9875 // NetworkMonitor is created. If the network disconnects or sends any other event
9876 // before that, messages are deferred by the Tracker Handler until it is (by asking
9877 // NetworkAgentInfo to do it). The window is very small unless the NetworkStack
9878 // doesn't reply immediately, which would mean a broken system anyway.
Chalard Jean8a976922025-03-18 09:27:33 +09009879 final NetworkAndAgentRegistryParcelable result = new NetworkAndAgentRegistryParcelable();
9880 result.network = nai.network;
9881 result.registry = nai.getRegistry();
9882 return result;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009883 }
9884
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009885 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09009886 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09009887 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09009888 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09009889 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09009890 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
9891 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
9892 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09009893
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009894 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05009895 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08009896 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05009897 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009898
9899 try {
9900 networkMonitor.start();
9901 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08009902 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009903 }
Chalard Jean366c5252022-01-25 18:27:53 +09009904
Chalard Jean1e4c2182023-10-06 18:45:53 +09009905 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09009906 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009907 }
Chalard Jeanb3a53d02025-03-18 09:28:26 +09009908 nai.notifyRegistered(networkMonitor);
Erik Kline286974f2018-03-04 21:01:01 +09009909 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09009910 updateNetworkInfo(nai, networkInfo);
Tommy Webba0dad0a2023-02-20 14:10:55 -05009911 updateDisallowedUidsForNetwork(nai);
Chalard Jean409913a2025-04-11 14:56:35 +09009912 if (nai.isVPN()) updateVpnUids(nai, null, nai.networkCapabilities);
Chalard Jeanc2cf5ea2025-03-17 14:36:03 +09009913 nai.processEnqueuedMessages(mTrackerHandler::handleMessage);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009914 }
9915
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009916 private class NetworkOfferInfo implements IBinder.DeathRecipient {
9917 @NonNull public final NetworkOffer offer;
9918
9919 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
9920 this.offer = offer;
9921 }
9922
9923 @Override
9924 public void binderDied() {
Patrick Rohre7a4b082024-12-17 19:02:11 -08009925 mHandler.post(() -> handleUnregisterNetworkOffer(this, true /* releaseReservations */));
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009926 }
9927 }
9928
Chalard Jeandd35f2d2021-03-24 14:31:38 +09009929 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
9930 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
9931 if (npi.providerId == providerId) return true;
9932 }
9933 return false;
9934 }
9935
Patrick Rohr73eee542024-12-06 12:29:29 -08009936 @Nullable
9937 private NetworkRequestInfo maybeGetNriForReservedOffer(NetworkOfferInfo noi) {
9938 final int reservationId = noi.offer.caps.getReservationId();
9939 if (reservationId == RES_ID_UNSET) return null; // not a reserved offer.
9940
9941 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
9942 if (reservationId == nri.getReservationId()) return nri;
9943 }
9944 // The reservation was withdrawn or the reserving process died.
9945 return null;
9946 }
9947
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009948 /**
9949 * Register or update a network offer.
9950 * @param newOffer The new offer. If the callback member is the same as an existing
9951 * offer, it is an update of that offer.
9952 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09009953 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009954 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
9955 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09009956 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009957 // This may actually happen if a provider updates its score or registers and then
9958 // immediately unregisters. The offer would still be in the handler queue, but the
9959 // provider would have been removed.
9960 if (DBG) log("Received offer from an unregistered provider");
9961 return;
9962 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009963 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
Patrick Rohre7a4b082024-12-17 19:02:11 -08009964
9965 // If a reserved offer is updated, ensure the capabilities are not changed. This ensures
9966 // that the reserved offer's capabilities match the ones passed by the onReserved callback,
9967 // which is sent only once.
9968 //
9969 // TODO: consider letting the provider change the capabilities of an offer as long as they
9970 // continue to satisfy the capabilities that were passed to onReserved. This is not needed
9971 // today, but it shouldn't violate the API contract:
9972 // - NetworkOffer capabilities are not promises
9973 // - The app making a reservation must never assume that the capabilities of the reserved
9974 // network are equal to the ones that were passed to onReserved. There will almost always be
9975 // other capabilities, for example, those that change at runtime such as VALIDATED or
9976 // NOT_SUSPENDED.
9977 if (null != existingOffer
9978 && existingOffer.offer.caps.getReservationId() != RES_ID_UNSET
9979 && existingOffer.offer.caps.getReservationId() != RES_ID_MATCH_ALL_RESERVATIONS
9980 && !newOffer.caps.equals(existingOffer.offer.caps)) {
9981 // Reserved offers are not allowed to update their NetworkCapabilities.
9982 // Doing so will immediately remove the offer from CS and send onUnavailable to the app.
9983 handleUnregisterNetworkOffer(existingOffer, true /* releaseReservations */);
9984 existingOffer.offer.notifyUnneeded();
9985 logwtf("Reserved offers must never update their reserved NetworkCapabilities");
9986 return;
9987 }
9988
9989 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009990 if (null != existingOffer) {
Patrick Rohre7a4b082024-12-17 19:02:11 -08009991 // Do not send onUnavailable for a reserved offer when updating it.
9992 handleUnregisterNetworkOffer(existingOffer, false /* releaseReservations */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09009993 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09009994 if (DBG) {
9995 // handleUnregisterNetworkOffer has already logged the old offer
9996 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
9997 }
9998 } else {
Patrick Rohre7a4b082024-12-17 19:02:11 -08009999 final NetworkRequestInfo reservationNri = maybeGetNriForReservedOffer(noi);
10000 if (reservationNri != null) {
10001 // A NetworkRequest is only allowed to trigger a single reserved offer (and
10002 // onReserved() callback). All subsequent offers are ignored. This either indicates
10003 // a bug in the provider (e.g., responding twice to the same reservation, or
10004 // updating the capabilities of a reserved offer), or multiple providers responding
10005 // to the same offer (which could happen, but is not useful to the requesting app).
10006 if (reservationNri.getReservedCapabilities() != null) {
10007 loge("A reservation can only trigger a single offer; new offer is ignored.");
10008 return;
10009 }
10010 // Always update the reserved offer before calling callCallbackForRequest.
10011 reservationNri.setReservedCapabilities(noi.offer.caps);
10012 callCallbackForRequest(
10013 reservationNri, null /*networkAgent*/, CALLBACK_RESERVED, 0 /*arg1*/);
10014 }
Chalard Jeanbb902a52021-08-18 01:35:19 +090010015 if (DBG) {
10016 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
10017 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +090010018 }
Patrick Rohr73eee542024-12-06 12:29:29 -080010019
Chalard Jeancdd68bc2021-01-05 08:40:09 +090010020 try {
Chalard Jean30689b82021-03-22 22:44:02 +090010021 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +090010022 } catch (RemoteException e) {
10023 noi.binderDied();
10024 return;
10025 }
10026 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010027 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +090010028 }
10029
Patrick Rohre7a4b082024-12-17 19:02:11 -080010030 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi,
10031 boolean releaseReservations) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +090010032 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +090010033 if (DBG) {
10034 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
10035 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -070010036
10037 // If the provider removes the offer and dies immediately afterwards this
10038 // function may be called twice in a row, but the array will no longer contain
10039 // the offer.
10040 if (!mNetworkOffers.remove(noi)) return;
Patrick Rohr73eee542024-12-06 12:29:29 -080010041
10042 // If the offer was brought up as a result of a reservation, inform the RESERVATION request
10043 // that it has disappeared. There is no need to reset nri.mReservedCapabilities to null, as
10044 // CALLBACK_UNAVAIL will cause the request to be torn down. In addition, leaving
10045 // nri.mReservedOffer set prevents an additional onReserved() callback in
10046 // handleRegisterNetworkOffer() in the case of a migration (which would be ignored as it
10047 // follows an onUnavailable).
10048 final NetworkRequestInfo nri = maybeGetNriForReservedOffer(noi);
Patrick Rohre7a4b082024-12-17 19:02:11 -080010049 if (releaseReservations && nri != null) {
Patrick Rohr73eee542024-12-06 12:29:29 -080010050 handleRemoveNetworkRequest(nri);
10051 callCallbackForRequest(nri, null /* networkAgent */, CALLBACK_UNAVAIL, 0 /* arg1 */);
10052 }
Chalard Jean30689b82021-03-22 22:44:02 +090010053 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +090010054 }
10055
10056 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
10057 @NonNull final INetworkOfferCallback callback) {
10058 ensureRunningOnConnectivityServiceThread();
10059 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +090010060 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +090010061 }
10062 return null;
10063 }
10064
Lorenzo Colitti129c01e2020-11-09 10:32:56 +090010065 /**
10066 * Called when receiving LinkProperties directly from a NetworkAgent.
10067 * Stores into |nai| any data coming from the agent that might also be written to the network's
10068 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
10069 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +090010070 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +090010071 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +090010072 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
10073 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +090010074 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -080010075 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +090010076 }
10077
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +090010078 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +080010079 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -080010080 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010081
Lorenzo Colittid523d142020-04-01 20:16:30 +090010082 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
10083 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
10084 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +090010085 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +090010086
Suprabh Shukla1e312032023-01-24 03:36:37 -080010087 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +000010088
10089 // update filtering rules, need to happen after the interface update so netd knows about the
10090 // new interface (the interface name -> index map becomes initialized)
10091 updateVpnFiltering(newLp, oldLp, networkAgent);
10092
Motomu Utsumib4772b12023-10-23 17:08:27 +090010093 updateIngressToVpnAddressFiltering(newLp, oldLp, networkAgent);
10094
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010095 updateMtu(newLp, oldLp);
10096 // TODO - figure out what to do for clat
10097// for (LinkProperties lp : newLp.getStackedLinks()) {
10098// updateMtu(lp, null);
10099// }
Chalard Jean5b409c72021-02-04 13:12:59 +090010100 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +080010101 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +080010102 updateTcpBufferSizes(newLp.getTcpBufferSizes());
10103 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +090010104
Erik Klineb9888902016-04-05 13:30:49 +090010105 updateRoutes(newLp, oldLp, netId);
10106 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -050010107 // Make sure LinkProperties represents the latest private DNS status.
10108 // This does not need to be done before updateDnses because the
10109 // LinkProperties are not the source of the private DNS configuration.
10110 // updateDnses will fetch the private DNS configuration from DnsManager.
10111 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +090010112
Chalard Jean5b409c72021-02-04 13:12:59 +090010113 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +080010114 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010115 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +090010116 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -050010117 }
Valentin Iftime9fa35092019-09-24 13:32:13 +020010118
10119 updateWakeOnLan(newLp);
10120
Hai Shalome58bdc62021-01-11 18:45:34 -080010121 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
10122 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
10123 // does, it needs to be merged here.
10124 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
10125 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +090010126
Robert Greenwalte525a0a2014-09-30 16:50:07 -070010127 // TODO - move this check to cover the whole function
10128 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +090010129 synchronized (networkAgent) {
10130 networkAgent.linkProperties = newLp;
10131 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +090010132 // Start or stop DNS64 detection and 464xlat according to network state.
10133 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +080010134 // Notify NSS when relevant events happened. Currently, NSS only cares about
10135 // interface changed to update clat interfaces accounting.
10136 final boolean interfacesChanged = oldLp == null
10137 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
10138 if (interfacesChanged) {
10139 notifyIfacesChangedForNetworkStats();
10140 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +090010141 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
10142 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090010143 notifyNetworkCallbacks(networkAgent, CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -070010144 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010145
10146 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -040010147 }
10148
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010149 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
10150 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
10151 }
10152
Hai Shalome58bdc62021-01-11 18:45:34 -080010153 /**
10154 * @param naData captive portal data from NetworkAgent
10155 * @param apiData captive portal data from capport API
10156 */
10157 @Nullable
10158 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
10159 CaptivePortalData apiData) {
10160 if (naData == null || apiData == null) {
10161 return naData == null ? apiData : naData;
10162 }
10163 final CaptivePortalData.Builder captivePortalBuilder =
10164 new CaptivePortalData.Builder(naData);
10165
10166 if (apiData.isCaptive()) {
10167 captivePortalBuilder.setCaptive(true);
10168 }
10169 if (apiData.isSessionExtendable()) {
10170 captivePortalBuilder.setSessionExtendable(true);
10171 }
10172 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
10173 // Expiry time, bytes remaining, refresh time all need to come from the same source,
10174 // otherwise data would be inconsistent. Prefer the capport API info if present,
10175 // as it can generally be refreshed more often.
10176 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
10177 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
10178 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
10179 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
10180 // No source has time / bytes remaining information: surface the newest refresh time
10181 // for other fields
10182 captivePortalBuilder.setRefreshTime(
10183 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
10184 }
10185
Hai Shalom7c6ab402021-02-04 19:34:06 -080010186 // Prioritize the user portal URL from the network agent if the source is authenticated.
10187 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
10188 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
10189 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
10190 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -080010191 }
Hai Shalom7c6ab402021-02-04 19:34:06 -080010192 // Prioritize the venue information URL from the network agent if the source is
10193 // authenticated.
10194 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
10195 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
10196 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
10197 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -080010198 }
10199 return captivePortalBuilder.build();
10200 }
10201
Suprabh Shukla53e16392023-04-26 18:47:36 -070010202 @VisibleForTesting
10203 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -080010204 // This needs to be kept in sync and backwards compatible with the decoding logic in
10205 // NetdEventListenerService, which is non-mainline code.
10206 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
10207 }
10208
Suprabh Shukla75642282023-04-25 23:15:43 -070010209 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
10210 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
10211 return true;
10212 }
10213 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
10214 return true;
10215 }
10216 return false;
10217 }
10218
Suprabh Shukla1e312032023-01-24 03:36:37 -080010219 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +090010220 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +090010221 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -070010222 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +090010223 return;
10224 }
Joel Scherpelza235a812017-05-22 13:47:41 +090010225
Joel Scherpelz946a3c92017-06-08 15:35:21 +090010226 // Mask/mark of zero will not detect anything interesting.
10227 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +000010228 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +090010229 return;
10230 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +090010231
Suprabh Shukla1e312032023-01-24 03:36:37 -080010232 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +090010233 try {
10234 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +000010235 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +090010236 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +000010237 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +090010238 }
10239 } catch (Exception e) {
10240 loge("Exception modifying wakeup packet monitoring: " + e);
10241 }
Joel Scherpelza235a812017-05-22 13:47:41 +090010242 }
10243
Junyu Lai970963e2022-10-25 15:46:47 +080010244 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +090010245 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -080010246 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +090010247 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +080010248 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +090010249 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +090010250 for (final String iface : interfaceDiff.added) {
10251 try {
10252 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +090010253 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -080010254 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +080010255 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -080010256 nai.networkCapabilities.getTransportTypes());
Sarup Dalwani53ecd952025-03-05 15:43:22 +000010257 mInterfaceTracker.addInterface(iface);
Chalard Jean9589e722019-11-19 19:03:53 +090010258 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +080010259 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +090010260 }
Paul Jensenbff73492014-04-28 10:33:11 -040010261 }
10262 }
Sarup Dalwani53ecd952025-03-05 15:43:22 +000010263
10264 // The local network addresses needs to be updated before interfaces are removed because
10265 // modifying bpf map local_net_access requires mapping interface name to index.
10266 updateLocalNetworkAddresses(newLp, oldLp);
10267
Chalard Jean9589e722019-11-19 19:03:53 +090010268 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -040010269 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -070010270 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -080010271 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +090010272 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Sarup Dalwani53ecd952025-03-05 15:43:22 +000010273 mInterfaceTracker.removeInterface(iface);
Paul Jensenbff73492014-04-28 10:33:11 -040010274 } catch (Exception e) {
10275 loge("Exception removing interface: " + e);
10276 }
10277 }
10278 }
10279
Paul Jensene0fd4a82014-08-06 15:51:33 -040010280 /**
Sarup Dalwani18b72622025-02-08 04:06:44 +000010281 * Update Local Network Addresses to LocalNetAccess BPF map.
10282 * @param newLp new link properties
10283 * @param oldLp old link properties
10284 */
10285 private void updateLocalNetworkAddresses(@Nullable final LinkProperties newLp,
10286 @NonNull final LinkProperties oldLp) {
10287
10288 // The maps are available only after 25Q2 release
10289 if (!BpfNetMaps.isAtLeast25Q2()) {
10290 return;
10291 }
10292
10293 final CompareResult<String> interfaceDiff = new CompareResult<>(
10294 oldLp != null ? oldLp.getAllInterfaceNames() : null,
10295 newLp != null ? newLp.getAllInterfaceNames() : null);
10296
10297 for (final String iface : interfaceDiff.added) {
Neha Raj4792cc52025-02-13 00:46:25 +000010298 addLocalAddressesToBpfMap(iface, MULTICAST_AND_BROADCAST_PREFIXES, newLp);
Sarup Dalwani18b72622025-02-08 04:06:44 +000010299 }
10300 for (final String iface : interfaceDiff.removed) {
Neha Raj4792cc52025-02-13 00:46:25 +000010301 removeLocalAddressesFromBpfMap(iface, MULTICAST_AND_BROADCAST_PREFIXES, oldLp);
Sarup Dalwani18b72622025-02-08 04:06:44 +000010302 }
10303
Sarup Dalwani7d0fcbb2025-02-18 19:08:04 +000010304 // The both list contain current link properties + stacked links for new and old LP.
Sarup Dalwanie53faa42025-02-20 05:44:56 +000010305 final List<LinkProperties> newLinkProperties = new ArrayList<>();
10306 final List<LinkProperties> oldLinkProperties = new ArrayList<>();
Sarup Dalwani18b72622025-02-08 04:06:44 +000010307
Sarup Dalwani18b72622025-02-08 04:06:44 +000010308 if (newLp != null) {
Sarup Dalwani7d0fcbb2025-02-18 19:08:04 +000010309 newLinkProperties.add(newLp);
10310 newLinkProperties.addAll(newLp.getStackedLinks());
10311 }
10312 if (oldLp != null) {
10313 oldLinkProperties.add(oldLp);
10314 oldLinkProperties.addAll(oldLp.getStackedLinks());
10315 }
10316
10317 // map contains interface name to list of local network prefixes added because of change
10318 // in link properties
Sarup Dalwanie53faa42025-02-20 05:44:56 +000010319 final Map<String, List<IpPrefix>> prefixesAddedForInterface = new ArrayMap<>();
Sarup Dalwani7d0fcbb2025-02-18 19:08:04 +000010320
10321 final CompareResult<LinkProperties> linkPropertiesDiff = new CompareResult<>(
10322 oldLinkProperties, newLinkProperties);
10323
10324 for (LinkProperties linkProperty : linkPropertiesDiff.added) {
Sarup Dalwanie53faa42025-02-20 05:44:56 +000010325 final List<IpPrefix> unicastLocalPrefixesToBeAdded = new ArrayList<>();
Sarup Dalwani7d0fcbb2025-02-18 19:08:04 +000010326 for (LinkAddress linkAddress : linkProperty.getLinkAddresses()) {
Sarup Dalwani18b72622025-02-08 04:06:44 +000010327 unicastLocalPrefixesToBeAdded.addAll(
10328 getLocalNetworkPrefixesForAddress(linkAddress));
10329 }
Sarup Dalwani7d0fcbb2025-02-18 19:08:04 +000010330 addLocalAddressesToBpfMap(linkProperty.getInterfaceName(),
10331 unicastLocalPrefixesToBeAdded, linkProperty);
Sarup Dalwani18b72622025-02-08 04:06:44 +000010332
Sarup Dalwanie53faa42025-02-20 05:44:56 +000010333 // populating interface name -> ip prefixes which were added to local_net_access map.
Sarup Dalwani7d0fcbb2025-02-18 19:08:04 +000010334 if (!prefixesAddedForInterface.containsKey(linkProperty.getInterfaceName())) {
10335 prefixesAddedForInterface.put(linkProperty.getInterfaceName(), new ArrayList<>());
Sarup Dalwani18b72622025-02-08 04:06:44 +000010336 }
Sarup Dalwani7d0fcbb2025-02-18 19:08:04 +000010337 prefixesAddedForInterface.get(linkProperty.getInterfaceName())
10338 .addAll(unicastLocalPrefixesToBeAdded);
Sarup Dalwani18b72622025-02-08 04:06:44 +000010339 }
10340
Sarup Dalwani7d0fcbb2025-02-18 19:08:04 +000010341 for (LinkProperties linkProperty : linkPropertiesDiff.removed) {
Sarup Dalwanie53faa42025-02-20 05:44:56 +000010342 final List<IpPrefix> unicastLocalPrefixesToBeRemoved = new ArrayList<>();
10343 final List<IpPrefix> unicastLocalPrefixesAdded = prefixesAddedForInterface.getOrDefault(
10344 linkProperty.getInterfaceName(), Collections.emptyList());
Sarup Dalwani7d0fcbb2025-02-18 19:08:04 +000010345
10346 for (LinkAddress linkAddress : linkProperty.getLinkAddresses()) {
10347 unicastLocalPrefixesToBeRemoved.addAll(
10348 getLocalNetworkPrefixesForAddress(linkAddress));
10349 }
10350
10351 // This is to ensure if 10.0.10.0/24 was added and 10.0.11.0/24 was removed both will
Sarup Dalwanie53faa42025-02-20 05:44:56 +000010352 // still populate the same prefix of 10.0.0.0/8, which mean 10.0.0.0/8 should not be
10353 // removed due to removal of 10.0.11.0/24
Sarup Dalwani7d0fcbb2025-02-18 19:08:04 +000010354 unicastLocalPrefixesToBeRemoved.removeAll(unicastLocalPrefixesAdded);
10355
10356 removeLocalAddressesFromBpfMap(linkProperty.getInterfaceName(),
10357 new ArrayList<>(unicastLocalPrefixesToBeRemoved), linkProperty);
10358 }
Sarup Dalwani18b72622025-02-08 04:06:44 +000010359 }
10360
10361 /**
10362 * Filters IpPrefix that are local prefixes and LinkAddress is part of them.
10363 * @param linkAddress link address used for filtering
10364 * @return list of IpPrefix that are local addresses.
10365 */
10366 private List<IpPrefix> getLocalNetworkPrefixesForAddress(LinkAddress linkAddress) {
10367 List<IpPrefix> localPrefixes = new ArrayList<>();
10368 if (linkAddress.isIpv6()) {
10369 // For IPv6, if the prefix length is greater than zero then they are part of local
10370 // network
10371 if (linkAddress.getPrefixLength() != 0) {
10372 localPrefixes.add(
10373 new IpPrefix(linkAddress.getAddress(), linkAddress.getPrefixLength()));
10374 }
10375 } else {
10376 // For IPv4, if the linkAddress is part of IpPrefix adding prefix to result.
10377 for (IpPrefix ipv4LocalPrefix : IPV4_LOCAL_PREFIXES) {
10378 if (ipv4LocalPrefix.containsPrefix(
10379 new IpPrefix(linkAddress.getAddress(), linkAddress.getPrefixLength()))) {
10380 localPrefixes.add(ipv4LocalPrefix);
10381 }
10382 }
10383 }
10384 return localPrefixes;
10385 }
10386
10387 /**
10388 * Adds list of prefixes(addresses) to local network access map.
10389 * @param iface interface name
10390 * @param prefixes list of prefixes/addresses
Neha Raj4792cc52025-02-13 00:46:25 +000010391 * @param lp LinkProperties
Sarup Dalwani18b72622025-02-08 04:06:44 +000010392 */
Neha Raj4792cc52025-02-13 00:46:25 +000010393 private void addLocalAddressesToBpfMap(final String iface, final List<IpPrefix> prefixes,
10394 @Nullable final LinkProperties lp) {
Sarup Dalwani18b72622025-02-08 04:06:44 +000010395 if (!BpfNetMaps.isAtLeast25Q2()) return;
Neha Raj4792cc52025-02-13 00:46:25 +000010396
Sarup Dalwani18b72622025-02-08 04:06:44 +000010397 for (IpPrefix prefix : prefixes) {
Neha Raj4792cc52025-02-13 00:46:25 +000010398 // Add local dnses allow rule To BpfMap before adding the block rule for prefix
10399 addLocalDnsesToBpfMap(iface, prefix, lp);
Sarup Dalwani18b72622025-02-08 04:06:44 +000010400 /*
10401 Prefix length is used by LPM trie map(local_net_access_map) for performing longest
10402 prefix matching, this length represents the maximum number of bits used for matching.
10403 The interface index should always be matched which is 32-bit integer. For IPv6, prefix
10404 length is calculated by adding the ip address prefix length along with interface index
10405 making it (32 + length). IPv4 addresses are stored as ipv4-mapped-ipv6 which implies
10406 first 96 bits are common for all ipv4 addresses. Hence, prefix length is calculated as
10407 32(interface index) + 96 (common for ipv4-mapped-ipv6) + length.
10408 */
10409 final int prefixLengthConstant = (prefix.isIPv4() ? (32 + 96) : 32);
10410 mBpfNetMaps.addLocalNetAccess(prefixLengthConstant + prefix.getPrefixLength(),
10411 iface, prefix.getAddress(), 0, 0, false);
10412
10413 }
10414
10415 }
10416
10417 /**
10418 * Removes list of prefixes(addresses) from local network access map.
10419 * @param iface interface name
10420 * @param prefixes list of prefixes/addresses
Neha Raj4792cc52025-02-13 00:46:25 +000010421 * @param lp LinkProperties
Sarup Dalwani18b72622025-02-08 04:06:44 +000010422 */
Neha Raj4792cc52025-02-13 00:46:25 +000010423 private void removeLocalAddressesFromBpfMap(final String iface, final List<IpPrefix> prefixes,
10424 @Nullable final LinkProperties lp) {
Sarup Dalwani18b72622025-02-08 04:06:44 +000010425 if (!BpfNetMaps.isAtLeast25Q2()) return;
Neha Raj4792cc52025-02-13 00:46:25 +000010426
Sarup Dalwani18b72622025-02-08 04:06:44 +000010427 for (IpPrefix prefix : prefixes) {
10428 // The reasoning for prefix length is explained in addLocalAddressesToBpfMap()
10429 final int prefixLengthConstant = (prefix.isIPv4() ? (32 + 96) : 32);
10430 mBpfNetMaps.removeLocalNetAccess(prefixLengthConstant
10431 + prefix.getPrefixLength(), iface, prefix.getAddress(), 0, 0);
Neha Raj4792cc52025-02-13 00:46:25 +000010432
10433 // Also remove the allow rule for dnses included in the prefix after removing the block
10434 // rule for prefix.
10435 removeLocalDnsesFromBpfMap(iface, prefix, lp);
Sarup Dalwani18b72622025-02-08 04:06:44 +000010436 }
10437 }
10438
10439 /**
Neha Raj4792cc52025-02-13 00:46:25 +000010440 * Adds DNS servers to local network access map, if included in the interface prefix
10441 * @param iface interface name
10442 * @param prefix IpPrefix
10443 * @param lp LinkProperties
10444 */
10445 private void addLocalDnsesToBpfMap(final String iface, IpPrefix prefix,
10446 @Nullable final LinkProperties lp) {
10447 if (!BpfNetMaps.isAtLeast25Q2() || lp == null) return;
10448
10449 for (InetAddress dnsServer : lp.getDnsServers()) {
10450 // Adds dns allow rule to LocalNetAccessMap for both TCP and UDP protocol at port 53,
10451 // if it is a local dns (ie. it falls in the local prefix range).
10452 if (prefix.contains(dnsServer)) {
Maciej Żenczykowski0c42bc42025-03-19 21:38:05 -070010453 mBpfNetMaps.addLocalNetAccess(32 + 128 + 16 + 16, iface, dnsServer,
Neha Raj4792cc52025-02-13 00:46:25 +000010454 IPPROTO_UDP, 53, true);
Maciej Żenczykowski0c42bc42025-03-19 21:38:05 -070010455 mBpfNetMaps.addLocalNetAccess(32 + 128 + 16 + 16, iface, dnsServer,
Neha Raj4792cc52025-02-13 00:46:25 +000010456 IPPROTO_TCP, 53, true);
Maciej Żenczykowski0c42bc42025-03-19 21:38:05 -070010457 mBpfNetMaps.addLocalNetAccess(32 + 128 + 16 + 16, iface, dnsServer,
Maciej Żenczykowskif236e862025-03-19 21:14:24 -070010458 IPPROTO_TCP, 853, true); // DNS over TLS
Neha Raj4792cc52025-02-13 00:46:25 +000010459 }
10460 }
10461 }
10462
10463 /**
10464 * Removes DNS servers from local network access map, if included in the interface prefix
10465 * @param iface interface name
10466 * @param prefix IpPrefix
10467 * @param lp LinkProperties
10468 */
10469 private void removeLocalDnsesFromBpfMap(final String iface, IpPrefix prefix,
10470 @Nullable final LinkProperties lp) {
10471 if (!BpfNetMaps.isAtLeast25Q2() || lp == null) return;
10472
10473 for (InetAddress dnsServer : lp.getDnsServers()) {
10474 // Removes dns allow rule from LocalNetAccessMap for both TCP and UDP protocol
10475 // at port 53, if it is a local dns (ie. it falls in the prefix range).
10476 if (prefix.contains(dnsServer)) {
Maciej Żenczykowski0c42bc42025-03-19 21:38:05 -070010477 mBpfNetMaps.removeLocalNetAccess(32 + 128 + 16 + 16, iface, dnsServer,
Neha Raj4792cc52025-02-13 00:46:25 +000010478 IPPROTO_UDP, 53);
Maciej Żenczykowski0c42bc42025-03-19 21:38:05 -070010479 mBpfNetMaps.removeLocalNetAccess(32 + 128 + 16 + 16, iface, dnsServer,
Neha Raj4792cc52025-02-13 00:46:25 +000010480 IPPROTO_TCP, 53);
Maciej Żenczykowski0c42bc42025-03-19 21:38:05 -070010481 mBpfNetMaps.removeLocalNetAccess(32 + 128 + 16 + 16, iface, dnsServer,
Maciej Żenczykowskif236e862025-03-19 21:14:24 -070010482 IPPROTO_TCP, 853); // DNS over TLS
Neha Raj4792cc52025-02-13 00:46:25 +000010483 }
10484 }
10485 }
10486
10487 /**
Paul Jensene0fd4a82014-08-06 15:51:33 -040010488 * Have netd update routes from oldLp to newLp.
10489 * @return true if routes changed between oldLp and newLp
10490 */
Junyu Lai970963e2022-10-25 15:46:47 +080010491 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
10492 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -080010493 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +080010494 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
10495 new CompareOrUpdateResult<>(
10496 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +080010497 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +080010498 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010499
10500 // add routes before removing old in case it helps with continuous connectivity
10501
Chalard Jean9dd11612018-06-04 16:52:49 +090010502 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010503 for (RouteInfo route : routeDiff.added) {
10504 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010505 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010506 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +090010507 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010508 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -070010509 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +090010510 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -070010511 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010512 }
10513 }
10514 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +090010515 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010516 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010517 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +090010518 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010519 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -070010520 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +090010521 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -070010522 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010523 }
10524 }
10525
10526 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010527 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010528 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +090010529 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010530 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +090010531 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010532 }
10533 }
Tyler Weare4314862019-12-05 14:55:30 -080010534
10535 for (RouteInfo route : routeDiff.updated) {
10536 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
10537 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +090010538 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -080010539 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +090010540 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -080010541 }
10542 }
10543 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
10544 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010545 }
Erik Kline0f0dbb82015-06-17 13:19:54 +090010546
Junyu Lai970963e2022-10-25 15:46:47 +080010547 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
10548 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +090010549 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
10550 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010551 }
Erik Klineb9888902016-04-05 13:30:49 +090010552
Erik Kline31b4a9e2018-01-11 21:07:29 +090010553 if (DBG) {
10554 final Collection<InetAddress> dnses = newLp.getDnsServers();
10555 log("Setting DNS servers for network " + netId + " to " + dnses);
10556 }
Erik Klineb9888902016-04-05 13:30:49 +090010557 try {
chenbruce7b2f8982020-02-20 14:28:31 +080010558 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +080010559 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +090010560 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +090010561 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +090010562 }
Erik Kline54e35c02017-04-07 15:29:29 +090010563 }
10564
Junyu Lai970963e2022-10-25 15:46:47 +080010565 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
10566 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +000010567 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
10568 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +000010569 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
10570 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +000010571
10572 if (!wasFiltering && !needsFiltering) {
10573 // Nothing to do.
10574 return;
10575 }
10576
10577 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
10578 // Nothing changed.
10579 return;
10580 }
10581
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010582 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +000010583 if (ranges == null || ranges.isEmpty()) {
10584 return;
10585 }
10586
Qingxi Libb8da982020-01-17 17:54:27 -080010587 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +000010588 // TODO: this create a window of opportunity for apps to receive traffic between the time
10589 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -060010590 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +000010591 // old rules are being removed.
10592 if (wasFiltering) {
10593 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
10594 }
10595 if (needsFiltering) {
10596 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
10597 }
10598 }
10599
Motomu Utsumib4772b12023-10-23 17:08:27 +090010600 /**
10601 * Returns ingress discard rules to drop packets to VPN addresses ingressing via non-VPN
10602 * interfaces.
10603 * Ingress discard rule is added to the address iff
10604 * 1. The address is not a link local address
Lorenzo Colittifd89cf52025-03-18 13:13:45 +090010605 * 2. The address is used by a single interface of VPN whose VPN type is not LEGACY, OEM or
10606 * OEM_LEGACY and the address is not used by any other interfaces even non-VPN ones
Motomu Utsumic14288f2024-08-06 19:00:22 +090010607 * Ingress discard rule is not be added to TYPE_VPN_LEGACY or TYPE_VPN_OEM VPN since these VPNs
10608 * might need to receive packet to VPN address via non-VPN interface.
Motomu Utsumib4772b12023-10-23 17:08:27 +090010609 * This method can be called during network disconnects, when nai has already been removed from
10610 * mNetworkAgentInfos.
10611 *
10612 * @param nai This method generates rules assuming lp of this nai is the lp at the second
10613 * argument.
10614 * @param lp This method generates rules assuming lp of nai at the first argument is this lp.
10615 * Caller passes old lp to generate old rules and new lp to generate new rules.
10616 * @return ingress discard rules. Set of pairs of addresses and interface names
10617 */
10618 private Set<Pair<InetAddress, String>> generateIngressDiscardRules(
10619 @NonNull final NetworkAgentInfo nai, @Nullable final LinkProperties lp) {
10620 Set<NetworkAgentInfo> nais = new ArraySet<>(mNetworkAgentInfos);
10621 nais.add(nai);
10622 // Determine how many networks each IP address is currently configured on.
10623 // Ingress rules are added only for IP addresses that are configured on single interface.
10624 final Map<InetAddress, Integer> addressOwnerCounts = new ArrayMap<>();
10625 for (final NetworkAgentInfo agent : nais) {
10626 if (agent.isDestroyed()) {
10627 continue;
10628 }
10629 final LinkProperties agentLp = (nai == agent) ? lp : agent.linkProperties;
10630 if (agentLp == null) {
10631 continue;
10632 }
10633 for (final InetAddress addr: agentLp.getAllAddresses()) {
10634 addressOwnerCounts.put(addr, addressOwnerCounts.getOrDefault(addr, 0) + 1);
10635 }
10636 }
10637
10638 // Iterates all networks instead of only generating rule for nai that was passed in since
10639 // lp of the nai change could cause/resolve address collision and result in affecting rule
10640 // for different network.
10641 final Set<Pair<InetAddress, String>> ingressDiscardRules = new ArraySet<>();
10642 for (final NetworkAgentInfo agent : nais) {
Motomu Utsumic14288f2024-08-06 19:00:22 +090010643 final int vpnType = getVpnType(agent);
Lorenzo Colittifd89cf52025-03-18 13:13:45 +090010644 if (!agent.isVPN() || agent.isDestroyed() || !vpnSupportsInterfaceFiltering(agent)) {
Motomu Utsumib4772b12023-10-23 17:08:27 +090010645 continue;
10646 }
10647 final LinkProperties agentLp = (nai == agent) ? lp : agent.linkProperties;
10648 if (agentLp == null || agentLp.getInterfaceName() == null) {
10649 continue;
10650 }
10651
10652 for (final InetAddress addr: agentLp.getAllAddresses()) {
10653 if (addressOwnerCounts.get(addr) == 1 && !addr.isLinkLocalAddress()) {
10654 ingressDiscardRules.add(new Pair<>(addr, agentLp.getInterfaceName()));
10655 }
10656 }
10657 }
10658 return ingressDiscardRules;
10659 }
10660
10661 private void updateIngressToVpnAddressFiltering(@Nullable LinkProperties newLp,
10662 @Nullable LinkProperties oldLp, @NonNull NetworkAgentInfo nai) {
10663 // Having isAtleastT to avoid NewApi linter error (b/303382209)
10664 if (!mIngressToVpnAddressFiltering || !mDeps.isAtLeastT()) {
10665 return;
10666 }
10667 final CompareOrUpdateResult<InetAddress, Pair<InetAddress, String>> ruleDiff =
10668 new CompareOrUpdateResult<>(
10669 generateIngressDiscardRules(nai, oldLp),
10670 generateIngressDiscardRules(nai, newLp),
10671 (rule) -> rule.first);
10672 for (Pair<InetAddress, String> rule: ruleDiff.removed) {
10673 mBpfNetMaps.removeIngressDiscardRule(rule.first);
10674 }
10675 for (Pair<InetAddress, String> rule: ruleDiff.added) {
10676 mBpfNetMaps.setIngressDiscardRule(rule.first, rule.second);
10677 }
10678 // setIngressDiscardRule overrides the existing rule
10679 for (Pair<InetAddress, String> rule: ruleDiff.updated) {
10680 mBpfNetMaps.setIngressDiscardRule(rule.first, rule.second);
10681 }
10682 }
10683
Valentin Iftime9fa35092019-09-24 13:32:13 +020010684 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010685 if (mWolSupportedInterfaces == null) {
10686 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010687 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010688 }
Valentin Iftime9fa35092019-09-24 13:32:13 +020010689 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
10690 }
10691
Luke Huangb913c812018-08-24 20:33:16 +080010692 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +090010693 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +080010694 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +090010695 }
10696 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +080010697 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +090010698 }
Luke Huangb913c812018-08-24 20:33:16 +080010699 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +090010700 }
10701
Chalard Jean62edfd82019-12-02 18:39:29 +090010702 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
10703 @NonNull final NetworkCapabilities newNc) {
10704 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
10705 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +090010706 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +090010707 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -080010708 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +080010709 } catch (RemoteException | ServiceSpecificException e) {
10710 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +090010711 }
10712 }
10713 }
10714
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010715 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +090010716 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +090010717 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010718 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -080010719 underlyingNetworks = underlyingNetworksOrDefault(
10720 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +090010721 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +090010722 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
10723 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010724 // metered if any underlying is metered, or originally declared metered by the agent.
10725 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +090010726 boolean roaming = false; // roaming if any underlying is roaming
10727 boolean congested = false; // congested if any underlying is congested
10728 boolean suspended = true; // suspended if all underlying are suspended
10729
10730 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +080010731 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090010732 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +080010733 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +090010734 for (Network underlyingNetwork : underlyingNetworks) {
10735 final NetworkAgentInfo underlying =
10736 getNetworkAgentInfoForNetwork(underlyingNetwork);
10737 if (underlying == null) continue;
10738
10739 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
10740 hadUnderlyingNetworks = true;
10741 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +090010742 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090010743 }
10744
10745 // Merge capabilities of this underlying network. For bandwidth, assume the
10746 // worst case.
10747 downKbps = NetworkCapabilities.minBandwidth(downKbps,
10748 underlyingCaps.getLinkDownstreamBandwidthKbps());
10749 upKbps = NetworkCapabilities.minBandwidth(upKbps,
10750 underlyingCaps.getLinkUpstreamBandwidthKbps());
10751 // If this underlying network is metered, the VPN is metered (it may cost money
10752 // to send packets on this network).
10753 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
10754 // If this underlying network is roaming, the VPN is roaming (the billing structure
10755 // is different than the usual, local one).
10756 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
10757 // If this underlying network is congested, the VPN is congested (the current
10758 // condition of the network affects the performance of this network).
10759 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
10760 // If this network is not suspended, the VPN is not suspended (the VPN
10761 // is able to transfer some data).
10762 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +080010763 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +090010764 }
10765 }
10766 if (!hadUnderlyingNetworks) {
10767 // No idea what the underlying networks are; assume reasonable defaults
10768 metered = true;
10769 roaming = false;
10770 congested = false;
10771 suspended = false;
10772 }
10773
Chalard Jean1d420b32022-10-12 16:39:37 +090010774 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010775 newNc.setLinkDownstreamBandwidthKbps(downKbps);
10776 newNc.setLinkUpstreamBandwidthKbps(upKbps);
10777 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
10778 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
10779 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
10780 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +080010781 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +090010782 }
10783
Lorenzo Colitti129c01e2020-11-09 10:32:56 +090010784 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010785 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
10786 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
10787 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -040010788 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +090010789 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010790 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +090010791 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +090010792 // Don't complain for VPNs since they're not driven by requests and there is no risk of
10793 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +090010794 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +090010795 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +090010796 if (nai.everConnected()
10797 && !nai.isVPN()
10798 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010799 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +090010800 // does not cause any request (that is not a listen) currently matching that agent to
10801 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010802 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +090010803 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +080010804 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +090010805 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010806 }
10807
Paul Jensen53f08952015-06-16 14:27:36 -040010808 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +090010809 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +090010810 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010811 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -040010812 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010813 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -040010814 }
Chalard Jean254bd162022-08-25 13:04:51 +090010815 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010816 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -040010817 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010818 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -040010819 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010820 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010821 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010822 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010823 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010824 }
Chalard Jean254bd162022-08-25 13:04:51 +090010825 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +080010826 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
10827 } else {
10828 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
10829 }
lucasline117e2e2019-10-22 18:27:33 +080010830 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010831
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010832 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +090010833 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
10834 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010835 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +090010836 }
10837
Lorenzo Colittibd079452021-07-02 11:47:57 +090010838 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +090010839 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +090010840 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010841 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +090010842 }
10843
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010844 return newNc;
10845 }
10846
Lorenzo Colitti44840702021-01-11 22:27:57 +090010847 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
10848 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
10849 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10850 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10851 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
10852 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
10853 if (prevSuspended != suspended) {
10854 // TODO (b/73132094) : remove this call once the few users of onSuspended and
10855 // onResumed have been removed.
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090010856 notifyNetworkCallbacks(nai, suspended ? CALLBACK_SUSPENDED : CALLBACK_RESUMED);
Lorenzo Colitti44840702021-01-11 22:27:57 +090010857 }
10858 if (prevSuspended != suspended || prevRoaming != roaming) {
10859 // updateNetworkInfo will mix in the suspended info from the capabilities and
10860 // take appropriate action for the network having possibly changed state.
10861 updateNetworkInfo(nai, nai.networkInfo);
10862 }
10863 }
10864
Ying Xu0d06b942024-02-09 21:04:08 -080010865 private void handleUidCarrierPrivilegesLost(int uid, int subId) {
Motomu Utsumi4fcaa4e2024-02-28 17:15:41 +090010866 if (!mRequestRestrictedWifiEnabled) {
10867 return;
10868 }
Ying Xu7cabd322024-01-15 18:40:15 -080010869 ensureRunningOnConnectivityServiceThread();
10870 // A NetworkRequest needs to be revoked when all the conditions are met
10871 // 1. It requests restricted network
10872 // 2. The requestor uid matches the uid with the callback
10873 // 3. The app doesn't have Carrier Privileges
10874 // 4. The app doesn't have permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS
10875 for (final NetworkRequest nr : mNetworkRequests.keySet()) {
Ying Xu611b8042024-02-27 10:07:43 -080010876 if (nr.isRequest()
Ying Xu7cabd322024-01-15 18:40:15 -080010877 && !nr.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
10878 && nr.getRequestorUid() == uid
Ying Xu0d06b942024-02-09 21:04:08 -080010879 && getSubscriptionIdFromNetworkCaps(nr.networkCapabilities) == subId
Ying Xu7cabd322024-01-15 18:40:15 -080010880 && !hasConnectivityRestrictedNetworksPermission(uid, true)) {
10881 declareNetworkRequestUnfulfillable(nr);
10882 }
10883 }
10884
10885 // A NetworkAgent's allowedUids may need to be updated if the app has lost
10886 // carrier config
Chalard Jean2f52a0e2025-03-21 10:14:28 +090010887 forEachNetworkAgentInfo(nai -> {
Ying Xu0d06b942024-02-09 21:04:08 -080010888 if (nai.networkCapabilities.getAllowedUidsNoCopy().contains(uid)
10889 && getSubscriptionIdFromNetworkCaps(nai.networkCapabilities) == subId) {
Ying Xu7cabd322024-01-15 18:40:15 -080010890 final NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
10891 NetworkAgentInfo.restrictCapabilitiesFromNetworkAgent(
10892 nc,
10893 uid,
10894 false /* hasAutomotiveFeature (irrelevant) */,
10895 mDeps,
10896 mCarrierPrivilegeAuthenticator);
10897 updateCapabilities(nai.getScore(), nai, nc);
10898 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +090010899 });
Ying Xu7cabd322024-01-15 18:40:15 -080010900 }
10901
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010902 /**
10903 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
10904 *
10905 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
10906 * capabilities we manage and store in {@code nai}, such as validated status and captive
10907 * portal status)
10908 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
10909 * potentially triggers rematches.
10910 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
10911 * change.)
10912 *
10913 * @param oldScore score of the network before any of the changes that prompted us
10914 * to call this function.
10915 * @param nai the network having its capabilities updated.
10916 * @param nc the new network capabilities.
10917 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +090010918 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +090010919 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010920 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +090010921 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +090010922 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
10923 if (null != differences) {
10924 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
10925 }
Chalard Jean62edfd82019-12-02 18:39:29 +090010926 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +090010927 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -060010928
Tommy Webba0dad0a2023-02-20 14:10:55 -050010929 if (prevNc != null && (!prevNc.equalsUids(newNc) || !prevNc.equalsTransportTypes(newNc))) {
10930 updateDisallowedUidsForNetwork(nai);
10931 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010932 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +090010933 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +090010934 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +090010935
Chalard Jeanaa5bc622022-02-26 21:34:48 +090010936 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010937 // If the requestable capabilities haven't changed, and the score hasn't changed, then
10938 // the change we're processing can't affect any requests, it can only affect the listens
10939 // on this network. We might have been called by rematchNetworkAndRequests when a
10940 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +090010941 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010942 } else {
10943 // If the requestable capabilities have changed or the score changed, we can't have been
10944 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010945 rematchAllNetworksAndRequests();
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090010946 notifyNetworkCallbacks(nai, CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010947 }
Lorenzo Colitti44840702021-01-11 22:27:57 +090010948 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -060010949
Lorenzo Colitti59fa1272021-01-16 00:23:46 +090010950 final boolean oldMetered = prevNc.isMetered();
10951 final boolean newMetered = newNc.isMetered();
10952 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +080010953
Lorenzo Colitti59fa1272021-01-16 00:23:46 +090010954 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +000010955 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
10956 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +090010957 }
junyulaif2c67e42018-08-07 19:50:45 +080010958
Lorenzo Colitti59fa1272021-01-16 00:23:46 +090010959 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
10960 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +080010961
Lorenzo Colitti59fa1272021-01-16 00:23:46 +090010962 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +080010963 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +090010964 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -060010965 }
10966
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010967 // This network might have been underlying another network. Propagate its capabilities.
10968 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +080010969
Ken Chen5a35cf92023-10-07 07:54:22 +080010970 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +080010971 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +080010972 }
lucaslin53e8a262021-06-08 01:43:59 +080010973
10974 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010975 }
10976
Lorenzo Colittie4d1e522020-12-10 00:32:04 +090010977 /** Convenience method to update the capabilities for a given network. */
10978 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +090010979 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +090010980 }
10981
Yang Sun29037f62023-12-04 10:31:58 +080010982 private void maybeApplyMulticastRoutingConfig(@NonNull final NetworkAgentInfo nai,
10983 final LocalNetworkConfig oldConfig,
10984 final LocalNetworkConfig newConfig) {
10985 final MulticastRoutingConfig oldUpstreamConfig =
10986 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
10987 oldConfig.getUpstreamMulticastRoutingConfig();
10988 final MulticastRoutingConfig oldDownstreamConfig =
10989 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
10990 oldConfig.getDownstreamMulticastRoutingConfig();
10991 final MulticastRoutingConfig newUpstreamConfig =
10992 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
10993 newConfig.getUpstreamMulticastRoutingConfig();
10994 final MulticastRoutingConfig newDownstreamConfig =
10995 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
10996 newConfig.getDownstreamMulticastRoutingConfig();
10997
10998 if (oldUpstreamConfig.equals(newUpstreamConfig) &&
10999 oldDownstreamConfig.equals(newDownstreamConfig)) {
11000 return;
11001 }
11002
11003 final String downstreamNetworkName = nai.linkProperties.getInterfaceName();
11004 final LocalNetworkInfo lni = localNetworkInfoForNai(nai);
11005 final Network upstreamNetwork = lni.getUpstreamNetwork();
11006
11007 if (upstreamNetwork != null) {
11008 final String upstreamNetworkName =
11009 getLinkProperties(upstreamNetwork).getInterfaceName();
11010 applyMulticastRoutingConfig(downstreamNetworkName, upstreamNetworkName, newConfig);
11011 }
11012 }
11013
11014 private void applyMulticastRoutingConfig(@NonNull String localNetworkInterfaceName,
11015 @NonNull String upstreamNetworkInterfaceName,
11016 @NonNull final LocalNetworkConfig config) {
Yang Sunca537d52024-01-19 12:53:50 +080011017 if (mMulticastRoutingCoordinatorService == null) {
11018 if (config.getDownstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE ||
11019 config.getUpstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE) {
11020 loge("Multicast routing is not supported, failed to configure " + config
11021 + " for " + localNetworkInterfaceName + " to "
11022 + upstreamNetworkInterfaceName);
11023 }
11024 return;
11025 }
Yang Sun29037f62023-12-04 10:31:58 +080011026
11027 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
11028 upstreamNetworkInterfaceName, config.getUpstreamMulticastRoutingConfig());
11029 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
11030 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
11031 config.getDownstreamMulticastRoutingConfig());
11032 }
11033
11034 private void disableMulticastRouting(@NonNull String localNetworkInterfaceName,
11035 @NonNull String upstreamNetworkInterfaceName) {
Yang Sunca537d52024-01-19 12:53:50 +080011036 if (mMulticastRoutingCoordinatorService == null) {
11037 return;
11038 }
Yang Sun29037f62023-12-04 10:31:58 +080011039
11040 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
11041 upstreamNetworkInterfaceName, MulticastRoutingConfig.CONFIG_FORWARD_NONE);
11042 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
11043 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
11044 MulticastRoutingConfig.CONFIG_FORWARD_NONE);
11045 }
11046
Chalard Jean1e4c2182023-10-06 18:45:53 +090011047 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +090011048 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +090011049 @Nullable final LocalNetworkConfig oldConfig,
11050 @NonNull final LocalNetworkConfig newConfig) {
11051 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +090011052 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
11053 return;
11054 }
Chalard Jean1e4c2182023-10-06 18:45:53 +090011055
Chalard Jean4fe23392023-10-17 23:02:27 +090011056 if (VDBG) {
11057 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
11058 }
Chalard Jean1e4c2182023-10-06 18:45:53 +090011059 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
Chalard Jean1e4c2182023-10-06 18:45:53 +090011060 configBuilder.setUpstreamMulticastRoutingConfig(
11061 newConfig.getUpstreamMulticastRoutingConfig());
11062 configBuilder.setDownstreamMulticastRoutingConfig(
11063 newConfig.getDownstreamMulticastRoutingConfig());
11064
11065 final NetworkRequest oldRequest =
11066 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
11067 final NetworkCapabilities oldCaps =
11068 (null == oldRequest) ? null : oldRequest.networkCapabilities;
11069 final NetworkRequestInfo oldNri =
11070 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
11071 final NetworkAgentInfo oldSatisfier =
11072 null == oldNri ? null : oldNri.getSatisfier();
11073 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
11074 final NetworkCapabilities newCaps =
11075 (null == newRequest) ? null : newRequest.networkCapabilities;
11076 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
11077 if (null != oldRequest && requestUpdated) {
11078 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
11079 if (null == newRequest && null != oldSatisfier) {
11080 // If there is an old satisfier, but no new request, then remove the old upstream.
11081 removeLocalNetworkUpstream(nai, oldSatisfier);
11082 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +090011083 // When there is a new request, the rematch sees the new request and sends the
11084 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
11085 // But here there is no new request, so the rematch won't see anything. Send
11086 // callbacks to apps now to tell them about the loss of upstream.
11087 notifyNetworkCallbacks(nai,
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090011088 CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090011089 return;
11090 }
11091 }
11092 if (null != newRequest && requestUpdated) {
11093 // File the new request if :
11094 // - it has changed (requestUpdated), or
11095 // - it's the first time this local info (null == oldConfig)
11096 // is updated and the request has not been filed yet.
11097 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
11098 // upstream (the best) but never request it to be brought up.
11099 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
11100 nextNetworkRequestId(), LISTEN_FOR_BEST);
11101 configBuilder.setUpstreamSelector(nr);
11102 final NetworkRequestInfo nri = new NetworkRequestInfo(
11103 nai.creatorUid, nr, null /* messenger */, null /* binder */,
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +090011104 0 /* callbackFlags */, null /* attributionTag */,
11105 DECLARED_METHODS_NONE);
Chalard Jean1e4c2182023-10-06 18:45:53 +090011106 if (null != oldSatisfier) {
11107 // Set the old satisfier in the new NRI so that the rematch will see any changes
11108 nri.setSatisfier(oldSatisfier, nr);
11109 }
11110 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +090011111 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
11112 // nai.localNetworkConfig is set, since it will base its callbacks on the old
11113 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +090011114 handleRegisterNetworkRequest(nri);
11115 } else {
11116 configBuilder.setUpstreamSelector(oldRequest);
11117 nai.localNetworkConfig = configBuilder.build();
11118 }
Yang Sun29037f62023-12-04 10:31:58 +080011119 maybeApplyMulticastRoutingConfig(nai, oldConfig, newConfig);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +090011120 }
11121
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011122 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +000011123 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011124 *
11125 * Ingress interface filtering enforces that all apps under the given network can only receive
11126 * packets from the network's interface (and loopback). This is important for VPNs because
11127 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
11128 * non-VPN interfaces.
11129 *
Motomu Utsumi77a79482022-05-16 04:04:34 +000011130 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011131 * 1. the network is an app VPN (not legacy VPN)
11132 * 2. the VPN does not allow bypass
11133 * 3. the VPN is fully-routed
11134 * 4. the VPN interface is non-null
11135 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +090011136 * @see INetd#firewallAddUidInterfaceRules
11137 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011138 */
Motomu Utsumi77a79482022-05-16 04:04:34 +000011139 @Nullable
11140 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011141 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +000011142 if (nc == null || lp == null) return null;
11143 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090011144 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -080011145 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011146 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +080011147 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +000011148 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +000011149 && !lp.hasExcludeRoute()) {
11150 return lp.getInterfaceName();
11151 }
11152 return null;
11153 }
11154
11155 /**
11156 * Returns whether we need to set interface filtering rule or not
11157 */
Motomu Utsumib08654c2022-05-11 05:56:26 +000011158 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +000011159 String isolationIface) {
11160 // Allow rules are always needed if VPN isolation is enabled.
11161 if (isolationIface != null) return true;
11162
11163 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
11164 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
11165 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +090011166 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011167 }
11168
Chiachang Wang28afaff2020-12-10 22:24:47 +080011169 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
11170 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
11171 int index = 0;
11172 for (UidRange range : ranges) {
11173 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
11174 index++;
11175 }
11176 return stableRanges;
11177 }
11178
Chalard Jeane6c95272022-01-25 21:04:21 +090011179 private static UidRangeParcel[] intsToUidRangeStableParcels(
11180 final @NonNull ArraySet<Integer> uids) {
11181 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
11182 int index = 0;
11183 for (int uid : uids) {
11184 stableRanges[index] = new UidRangeParcel(uid, uid);
11185 index++;
11186 }
11187 return stableRanges;
11188 }
11189
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090011190 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
11191 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
11192 for (int i = 0; i < ranges.length; i++) {
11193 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
11194 }
11195 return stableRanges;
11196 }
11197
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +090011198 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +080011199 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
11200 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +090011201 if (mDeps.isAtLeastU()) {
11202 final Set<Integer> exemptUidSet = new ArraySet<>();
11203 for (final int uid: exemptUids) {
11204 exemptUidSet.add(uid);
11205 }
11206 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
11207 } else {
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +090011208 mNetd.socketDestroy(toUidRangeStableParcels(ranges), exemptUids);
Motomu Utsumi1d137262023-06-04 21:32:08 +090011209 }
Ken Chen5e65a852020-12-24 12:59:10 +080011210 } catch (Exception e) {
11211 loge("Exception in socket destroy: ", e);
11212 }
11213 }
11214 }
11215
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +090011216 private void modifyNetworkUidRanges(boolean add, NetworkAgentInfo nai, UidRangeParcel[] ranges,
11217 int preference) throws RemoteException {
11218 // UID ranges can be added or removed to a network that has already been destroyed (e.g., if
11219 // the network disconnects, or a a multilayer request is filed after
11220 // unregisterAfterReplacement is called).
11221 if (nai.isDestroyed()) {
11222 return;
11223 }
11224 final NativeUidRangeConfig config = new NativeUidRangeConfig(nai.network.netId,
11225 ranges, preference);
11226 if (add) {
11227 mNetd.networkAddUidRangesParcel(config);
11228 } else {
11229 mNetd.networkRemoveUidRangesParcel(config);
11230 }
11231 }
11232
11233 private void modifyNetworkUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges,
11234 int preference) throws RemoteException {
11235 modifyNetworkUidRanges(add, nai, toUidRangeStableParcels(uidRanges), preference);
11236 }
11237
paulhuaa0743d2021-05-26 21:56:03 +080011238 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +090011239 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +080011240 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
11241 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
11242 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +090011243 exemptUids[0] = VPN_UID;
11244 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +080011245
Motomu Utsumi6345e462023-03-13 13:24:50 +090011246 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +090011247 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +080011248 try {
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +090011249 modifyNetworkUidRanges(add, nai, uidRanges, PREFERENCE_ORDER_VPN);
Ken Chen5e65a852020-12-24 12:59:10 +080011250 } catch (Exception e) {
11251 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
11252 " on netId " + nai.network.netId + ". " + e);
11253 }
Motomu Utsumi6345e462023-03-13 13:24:50 +090011254 // Close sockets that established connection while requesting netd.
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +090011255 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +080011256 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090011257
lucaslin53e8a262021-06-08 01:43:59 +080011258 private boolean isProxySetOnAnyDefaultNetwork() {
11259 ensureRunningOnConnectivityServiceThread();
11260 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
11261 final NetworkAgentInfo nai = nri.getSatisfier();
11262 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
11263 return true;
11264 }
11265 }
11266 return false;
11267 }
11268
11269 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
11270 NetworkCapabilities newNc) {
11271 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
11272 // the proxy might be changed since the default network satisfied by the apps might also
11273 // changed.
11274 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
11275 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +090011276 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
11277 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +090011278 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +080011279 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
11280 mProxyTracker.sendProxyBroadcast();
11281 }
11282 }
11283
Chalard Jeane6c95272022-01-25 21:04:21 +090011284 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
11285 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011286 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
11287 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +090011288 if (null == prevRanges) prevRanges = new ArraySet<>();
11289 if (null == newRanges) newRanges = new ArraySet<>();
11290 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
11291
11292 prevRanges.removeAll(newRanges);
11293 newRanges.removeAll(prevRangesCopy);
11294
11295 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011296 // When updating the VPN uid routing rules, add the new range first then remove the old
11297 // range. If old range were removed first, there would be a window between the old
11298 // range being removed and the new range being added, during which UIDs contained
11299 // in both ranges are not subject to any VPN routing rules. Adding new range before
11300 // removing old range works because, unlike the filtering rules below, it's possible to
11301 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +080011302 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
11303 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
11304 // [1-5] & [1-2],[4-5] == [3]
11305 // Then we can do:
11306 // maybeCloseSockets([3])
11307 // mNetd.networkAddUidRanges([1-2],[4-5])
11308 // mNetd.networkRemoveUidRanges([1-5])
11309 // maybeCloseSockets([3])
11310 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
11311 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +090011312 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +080011313 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +090011314 }
11315 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +080011316 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +090011317 }
Motomu Utsumi77a79482022-05-16 04:04:34 +000011318 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
11319 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +000011320 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
11321 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011322 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +090011323 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011324 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
11325 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
11326 // were added first and then newRanges got removed later, there would be only one uid
11327 // 10013 left. A consequence of removing old ranges before adding new ranges is that
11328 // there is now a window of opportunity when the UIDs are not subject to any filtering.
11329 // Note that this is in contrast with the (more robust) update of VPN routing rules
11330 // above, where the addition of new ranges happens before the removal of old ranges.
11331 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
11332 // to be removed will never overlap with the new range to be added.
11333 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +000011334 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
11335 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011336 }
11337 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +000011338 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +000011339 }
Chalard Jeanb2a49912018-01-16 18:43:05 +090011340 } catch (Exception e) {
11341 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000011342 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +090011343 }
11344 }
11345
Chalard Jeande665262022-02-25 16:12:12 +090011346 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +090011347 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
Tommy Webba0dad0a2023-02-20 14:10:55 -050011348 if (!nai.isVPN()) {
11349 updateAllowedUidsForNetwork(nai);
11350 }
Chalard Jeane6c95272022-01-25 21:04:21 +090011351 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +090011352 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
11353 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +090011354 if (prevEmpty && newEmpty) return;
11355
11356 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +090011357 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +090011358 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +090011359 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +090011360
11361 if (prevUids.equals(newUids)) return;
11362
11363 // This implementation is very simple and vastly faster for sets of Integers than
11364 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
11365 // a key computed from the value and has storage for that.
11366 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
11367 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
11368 toRemove.removeAll(newUids);
11369 toAdd.removeAll(prevUids);
Chalard Jeane6c95272022-01-25 21:04:21 +090011370 try {
11371 if (!toAdd.isEmpty()) {
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +090011372 modifyNetworkUidRanges(true /* add */, nai, intsToUidRangeStableParcels(toAdd),
11373 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT);
Chalard Jeane6c95272022-01-25 21:04:21 +090011374 }
11375 if (!toRemove.isEmpty()) {
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +090011376 modifyNetworkUidRanges(false /* add */, nai, intsToUidRangeStableParcels(toRemove),
11377 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT);
Chalard Jeane6c95272022-01-25 21:04:21 +090011378 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000011379 } catch (ServiceSpecificException e) {
11380 // Has the interface disappeared since the network was built ?
11381 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +090011382 } catch (RemoteException e) {
11383 // Netd died. This usually causes a runtime restart anyway.
11384 }
11385 }
11386
Junyu Lai2ed7d412022-10-07 16:52:21 +080011387 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
11388 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +090011389 ensureRunningOnConnectivityServiceThread();
11390
Lorenzo Colittib4bf0152021-06-07 15:32:04 +090011391 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +000011392 // Ignore updates for disconnected networks
11393 return;
11394 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090011395 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +090011396 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +090011397 + "; created=" + nai.getCreatedTime()
11398 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +000011399 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +090011400 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
11401 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +080011402 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +000011403 }
11404
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011405 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
11406 int notificationType) {
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090011407 if (notificationType == CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011408 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -080011409 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -080011410 // If apps could file multi-layer requests with PendingIntents, they'd need to know
11411 // which of the layer is satisfied alongside with some ID for the request. Hence, if
11412 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +090011413 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
11414 // need to be sent as a separate extra.
11415 final NetworkRequest req = nri.isMultilayerRequest()
11416 ? nri.getActiveRequest()
11417 // Non-multilayer listen requests do not have an active request
11418 : nri.mRequests.get(0);
11419 if (req == null) {
11420 Log.wtf(TAG, "No request in NRI " + nri);
11421 }
11422 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -080011423 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011424 sendIntent(nri.mPendingIntent, intent);
11425 }
11426 // else not handled
11427 }
11428
Chalard Jeanf34735e2025-02-07 16:11:46 +090011429 /**
11430 * A small class to manage releasing a lock exactly once even if releaseLock is called
11431 * multiple times. See b/390043283
11432 * PendingIntent#send throws CanceledException in various cases. In some of them it will
11433 * still call onSendFinished, in others it won't and the client can't know. This class
11434 * keeps a ref to the wakelock that it releases exactly once, thanks to Atomics semantics.
11435 */
11436 private class WakeLockOnFinishedReceiver implements PendingIntent.OnFinished {
11437 private final AtomicReference<PowerManager.WakeLock> mLock;
11438 WakeLockOnFinishedReceiver(@NonNull final PowerManager.WakeLock lock) {
11439 mLock = new AtomicReference<>(lock);
11440 lock.acquire();
11441 }
11442
11443 public void releaseLock() {
11444 final PowerManager.WakeLock lock = mLock.getAndSet(null);
11445 if (null != lock) lock.release();
11446 }
11447
11448 @Override
11449 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
11450 String resultData, Bundle resultExtras) {
11451 if (DBG) log("Finished sending " + pendingIntent);
11452 releaseLock();
11453 releasePendingNetworkRequestWithDelay(pendingIntent);
11454 }
11455 }
11456
Michael Groover73f69482023-01-27 11:01:25 -060011457 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
11458 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011459 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
Chalard Jeanf34735e2025-02-07 16:11:46 +090011460 // Since the receiver will take the lock exactly once and release it exactly once, it
11461 // is safe to pass the same wakelock to all receivers and avoid creating a new lock
11462 // every time.
11463 final WakeLockOnFinishedReceiver receiver =
11464 new WakeLockOnFinishedReceiver(mPendingIntentWakeLock);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011465 try {
11466 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +000011467 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +090011468 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +000011469 // Explicitly disallow the receiver from starting activities, to prevent apps from
11470 // utilizing the PendingIntent as a backdoor to do this.
11471 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
11472 }
Chalard Jeanf34735e2025-02-07 16:11:46 +090011473 pendingIntent.send(mContext, 0, intent, receiver, null /* Handler */,
chiachangwanga36518c2022-05-26 05:19:41 +000011474 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +090011475 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011476 } catch (PendingIntent.CanceledException e) {
11477 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
Chalard Jeanf34735e2025-02-07 16:11:46 +090011478 receiver.releaseLock();
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011479 releasePendingNetworkRequest(pendingIntent);
11480 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011481 }
11482
Chalard Jean22350c92023-10-07 19:21:45 +090011483 @Nullable
11484 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
11485 if (!nai.isLocalNetwork()) return null;
11486 final Network upstream;
11487 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
11488 if (null == selector) {
11489 upstream = null;
11490 } else {
11491 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
11492 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
11493 upstream = (null == satisfier) ? null : satisfier.network;
11494 }
11495 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
11496 }
11497
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +090011498 private Bundle makeCommonBundleForCallback(@NonNull final NetworkRequestInfo nri,
11499 @Nullable Network network) {
11500 final Bundle bundle = new Bundle();
11501 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
11502 // TODO: check if defensive copies of data is needed.
11503 putParcelable(bundle, nri.getNetworkRequestForCallback());
11504 if (network != null) {
11505 putParcelable(bundle, network);
11506 }
11507 return bundle;
11508 }
11509
Patrick Rohr73eee542024-12-06 12:29:29 -080011510 // networkAgent is only allowed to be null if notificationType is CALLBACK_UNAVAIL or
11511 // CALLBACK_RESERVED. This is because, per definition, no network is available for UNAVAIL, and
11512 // RESERVED callbacks happen when a NetworkOffer is created in response to a reservation.
James Mattis212df9e2020-12-03 19:57:41 -080011513 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +090011514 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -080011515 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -080011516 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011517 // Default request has no msgr. Also prevents callbacks from being invoked for
11518 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
11519 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
11520 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +090011521 }
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +090011522 // Even if a callback ends up not being sent, it may affect other callbacks in the queue, so
11523 // queue callbacks before checking the declared methods flags.
Patrick Rohr73eee542024-12-06 12:29:29 -080011524 // UNAVAIL and RESERVED callbacks are safe not to be queued, because RESERVED must always be
11525 // the first callback. In addition, RESERVED cannot be sent more than once and is only
11526 // cancelled by UNVAIL.
11527 // TODO: evaluate whether it makes sense to queue RESERVED callbacks.
Remi NGUYEN VAN2d781242024-06-05 18:57:40 +090011528 if (networkAgent != null && nri.maybeQueueCallback(networkAgent, notificationType)) {
11529 return;
11530 }
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +090011531 if (!nri.isCallbackOverridden(notificationType)) {
Remi NGUYEN VAN2fd38232024-05-28 15:25:43 +090011532 // No need to send the notification as the recipient method is not overridden
11533 return;
11534 }
Patrick Rohr73eee542024-12-06 12:29:29 -080011535 // networkAgent is only null for UNAVAIL and RESERVED.
11536 final Network bundleNetwork = (networkAgent != null) ? networkAgent.network : null;
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +090011537 final Bundle bundle = makeCommonBundleForCallback(nri, bundleNetwork);
Roshan Pius951c0032020-12-22 15:10:42 -080011538 final boolean includeLocationSensitiveInfo =
11539 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +090011540 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011541 switch (notificationType) {
Patrick Rohr73eee542024-12-06 12:29:29 -080011542 case CALLBACK_RESERVED: {
11543 final NetworkCapabilities nc =
11544 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
11545 networkCapabilitiesRestrictedForCallerPermissions(
11546 nri.getReservedCapabilities(), nri.mPid, nri.mUid),
11547 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
11548 nrForCallback.getRequestorPackageName(),
11549 nri.mCallingAttributionTag);
11550 putParcelable(bundle, nc);
11551 break;
11552 }
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090011553 case CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -080011554 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -080011555 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +090011556 networkCapabilitiesRestrictedForCallerPermissions(
11557 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
11558 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -080011559 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +090011560 nri.mCallingAttributionTag);
11561 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +090011562 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
11563 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +090011564 // The local network info is often null, so can't use the static putParcelable
11565 // method here.
11566 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
11567 localNetworkInfoForNai(networkAgent));
Robert Greenwalte525a0a2014-09-30 16:50:07 -070011568 break;
11569 }
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090011570 case CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +090011571 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -080011572 final NetworkCapabilities netCap =
11573 networkCapabilitiesRestrictedForCallerPermissions(
11574 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
11575 putParcelable(
11576 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -080011577 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -080011578 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -080011579 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -080011580 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -070011581 break;
11582 }
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090011583 case CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +090011584 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
11585 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011586 break;
11587 }
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090011588 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +090011589 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +080011590 break;
11591 }
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090011592 case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
Chalard Jean22350c92023-10-07 19:21:45 +090011593 if (!networkAgent.isLocalNetwork()) {
11594 Log.wtf(TAG, "Callback for local info for a non-local network");
11595 return;
11596 }
11597 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
11598 break;
11599 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011600 }
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +090011601 callCallbackForRequest(nri, notificationType, bundle, arg1);
11602 }
11603
11604 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri, int notificationType,
11605 Bundle bundle, int arg1) {
11606 Message msg = Message.obtain();
11607 msg.arg1 = arg1;
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011608 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -070011609 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011610 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -070011611 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090011612 String notification = ConnectivityManager.getCallbackName(notificationType);
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +090011613 log("sending notification " + notification + " for "
11614 + nri.getNetworkRequestForCallback());
Robert Greenwalt419e1b42014-08-27 14:34:02 -070011615 }
James Mattis45d81842021-01-10 14:24:24 -080011616 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011617 } catch (RemoteException e) {
11618 // may occur naturally in the race of binder death.
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +090011619 loge("RemoteException caught trying to send a callback msg for "
11620 + nri.getNetworkRequestForCallback());
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011621 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011622 }
11623
Hugo Benichif8a0f9f2017-03-23 22:40:44 +090011624 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
11625 bundle.putParcelable(t.getClass().getSimpleName(), t);
11626 }
11627
Chalard Jean0702f982021-09-16 21:50:07 +090011628 /**
11629 * Returns whether reassigning a request from an NAI to another can be done gracefully.
11630 *
11631 * When a request should be assigned to a new network, it is normally lingered to give
11632 * time for apps to gracefully migrate their connections. When both networks are on the same
11633 * radio, but that radio can't do time-sharing efficiently, this may end up being
11634 * counter-productive because any traffic on the old network may drastically reduce the
11635 * performance of the new network.
11636 * The stack supports a configuration to let modem vendors state that their radio can't
11637 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
11638 * from one cell network to another can't be done gracefully.
11639 *
11640 * @param oldNai the old network serving the request
11641 * @param newNai the new network serving the request
11642 * @return whether the switch can be graceful
11643 */
11644 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
11645 @NonNull final NetworkAgentInfo newSatisfier) {
11646 if (mCellularRadioTimesharingCapable) return true;
11647 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
11648 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
11649 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
11650 }
11651
Paul Jensenaf94b982014-09-30 15:37:41 -040011652 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +090011653 if (nai.numRequestNetworkRequests() != 0) {
11654 for (int i = 0; i < nai.numNetworkRequests(); i++) {
11655 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +090011656 // Ignore listening and track default requests.
11657 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +090011658 loge("Dead network still had at least " + nr);
11659 break;
11660 }
Paul Jensenaf94b982014-09-30 15:37:41 -040011661 }
Chalard Jean9fdc9882025-03-21 10:13:47 +090011662 if (mQueueNetworkAgentEventsInSystemServer) {
11663 disconnectAndDestroyNetwork(nai);
11664 } else {
11665 nai.disconnect();
11666 }
Paul Jensenaf94b982014-09-30 15:37:41 -040011667 }
11668
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011669 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
11670 if (oldNetwork == null) {
11671 loge("Unknown NetworkAgentInfo in handleLingerComplete");
11672 return;
11673 }
Chalard Jean49707572019-12-10 21:07:02 +090011674 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011675
11676 // If we get here it means that the last linger timeout for this network expired. So there
11677 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +080011678 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011679
Lorenzo Colitti2666be82016-09-09 18:48:56 +090011680 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090011681 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011682 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +090011683 } else {
junyulai0ac374f2020-12-14 18:41:52 +080011684 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +090011685 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011686 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011687 }
11688
James Mattise3ef1912020-12-20 11:09:58 -080011689 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
11690 boolean isDefaultChanged = false;
11691 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
11692 final NetworkReassignment.RequestReassignment reassignment =
11693 changes.getReassignment(defaultRequestInfo);
11694 if (null == reassignment) {
11695 continue;
11696 }
11697 // reassignment only contains those instances where the satisfying network changed.
11698 isDefaultChanged = true;
11699 // Notify system services of the new default.
11700 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
11701 }
Chiachang Wang087fd272018-09-28 22:42:48 +080011702
James Mattise3ef1912020-12-20 11:09:58 -080011703 if (isDefaultChanged) {
11704 // Hold a wakelock for a short time to help apps in migrating to a new default.
11705 scheduleReleaseNetworkTransitionWakelock();
11706 }
11707 }
11708
Aaron Huang9fe47be2021-06-08 13:11:45 +080011709 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
11710 if (null == oldDefaultNetwork) return;
11711 // The network stopped being the default. If it was using a PAC proxy, then the
11712 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
11713 // to the local proxy server, which would forward them over the newly default network.
11714 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
11715 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
11716 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
11717 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
11718 }
11719
James Mattise3ef1912020-12-20 11:09:58 -080011720 private void makeDefault(@NonNull final NetworkRequestInfo nri,
11721 @Nullable final NetworkAgentInfo oldDefaultNetwork,
11722 @Nullable final NetworkAgentInfo newDefaultNetwork) {
11723 if (DBG) {
11724 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
11725 }
Chalard Jean8e382112019-12-03 20:45:30 +090011726
James Mattisd31bdfa2020-12-23 16:37:26 -080011727 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
11728 if (newDefaultNetwork != null) {
11729 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -040011730 }
Lorenzo Colitti24861882018-01-19 00:50:48 +090011731
James Mattisd31bdfa2020-12-23 16:37:26 -080011732 // Set an app level managed default and return since further processing only applies to the
11733 // default network.
11734 if (mDefaultRequest != nri) {
11735 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
11736 return;
11737 }
11738
11739 makeDefaultNetwork(newDefaultNetwork);
11740
James Mattise3ef1912020-12-20 11:09:58 -080011741 if (oldDefaultNetwork != null) {
11742 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
11743 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090011744 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumidff5df52024-05-14 18:19:43 +090011745 maybeDestroyPendingSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +080011746 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -080011747 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +080011748 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -080011749 updateTcpBufferSizes(null != newDefaultNetwork
11750 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +090011751 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -040011752 }
11753
James Mattisd31bdfa2020-12-23 16:37:26 -080011754 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
11755 @Nullable final NetworkAgentInfo oldDefaultNetwork,
11756 @Nullable final NetworkAgentInfo newDefaultNetwork) {
11757 try {
11758 if (VDBG) {
11759 log("Setting default network for " + nri
11760 + " using UIDs " + nri.getUids()
11761 + " with old network " + (oldDefaultNetwork != null
11762 ? oldDefaultNetwork.network().getNetId() : "null")
11763 + " and new network " + (newDefaultNetwork != null
11764 ? newDefaultNetwork.network().getNetId() : "null"));
11765 }
11766 if (nri.getUids().isEmpty()) {
11767 throw new IllegalStateException("makeDefaultForApps called without specifying"
11768 + " any applications to set as the default." + nri);
11769 }
11770 if (null != newDefaultNetwork) {
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +090011771 modifyNetworkUidRanges(true /* add */, newDefaultNetwork, nri.getUids(),
11772 nri.getPreferenceOrderForNetd());
James Mattisd31bdfa2020-12-23 16:37:26 -080011773 }
11774 if (null != oldDefaultNetwork) {
Lorenzo Colittidfe98fc2024-10-07 11:45:04 +090011775 modifyNetworkUidRanges(false /* add */, oldDefaultNetwork, nri.getUids(),
11776 nri.getPreferenceOrderForNetd());
James Mattisd31bdfa2020-12-23 16:37:26 -080011777 }
11778 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +090011779 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -080011780 }
Tommy Webba0dad0a2023-02-20 14:10:55 -050011781 updateUidDefaultNetworkRules(newDefaultNetwork);
James Mattisd31bdfa2020-12-23 16:37:26 -080011782 }
11783
Junyu Lai35665cc2022-12-19 17:37:48 +080011784 /**
11785 * Collect restricted uid ranges for the given network and UserHandle, these uids
11786 * are not restricted for matched enterprise networks but being restricted for non-matched
11787 * enterprise networks and non-enterprise networks.
11788 */
11789 @NonNull
11790 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
11791 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
11792 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
11793 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
11794 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
11795
11796 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
11797 // The NC is built from a `ProfileNetworkPreference` which has only one
11798 // enterprise ID, so it's guaranteed to have exactly one.
11799 final int prefId = pref.capabilities.getEnterpriseIds()[0];
11800 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
11801 continue;
11802 }
11803 }
11804
11805 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
11806 pref.capabilities.getUidRanges())) {
11807 throw new IllegalArgumentException(
11808 "Overlapping uid range in preference: " + pref);
11809 }
11810 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
11811 }
11812 return restrictedUidRanges;
11813 }
11814
11815 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +080011816 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +090011817 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +080011818
Junyu Lai35665cc2022-12-19 17:37:48 +080011819 ensureRunningOnConnectivityServiceThread();
11820 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
11821 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
11822 .getUserHandles(true /* excludeDying */);
11823 if (users.isEmpty()) {
11824 throw new IllegalStateException("No user is available");
11825 }
11826
Chalard Jean2f52a0e2025-03-21 10:14:28 +090011827 forEachNetworkAgentInfo(nai -> {
Junyu Lai35665cc2022-12-19 17:37:48 +080011828 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
11829 for (final UserHandle user : users) {
11830 final ArraySet<UidRange> restrictedUidRanges =
11831 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
11832 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
11833 UidRange.createForUser(user), restrictedUidRanges));
11834 }
11835
11836 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
11837 configs.add(new NativeUidRangeConfig(
11838 nai.network.netId, rangesParcel, 0 /* subPriority */));
Chalard Jean2f52a0e2025-03-21 10:14:28 +090011839 });
Junyu Lai35665cc2022-12-19 17:37:48 +080011840
11841 // The netd API replaces the previous configs with the current configs.
11842 // Thus, for network disconnection or preference removal, no need to
11843 // unset previous config. Instead, collecting all currently needed
11844 // configs and issue to netd.
11845 try {
11846 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
11847 } catch (ServiceSpecificException e) {
11848 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +080011849 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +080011850 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +080011851 // Netd died. This will cause a runtime restart anyway.
11852 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +080011853 }
11854 }
11855
James Mattisd31bdfa2020-12-23 16:37:26 -080011856 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
11857 try {
11858 if (null != newDefaultNetwork) {
11859 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
11860 } else {
11861 mNetd.networkClearDefault();
11862 }
11863 } catch (RemoteException | ServiceSpecificException e) {
11864 loge("Exception setting default network :" + e);
11865 }
Tommy Webba0dad0a2023-02-20 14:10:55 -050011866 updateUidDefaultNetworkRules(newDefaultNetwork);
James Mattisd31bdfa2020-12-23 16:37:26 -080011867 }
11868
Chalard Jean05cbe972019-12-09 11:50:38 +090011869 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090011870 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +090011871 processNewlyLostListenRequests(nai);
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090011872 notifyNetworkCallbacks(nai, CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +090011873 processNewlySatisfiedListenRequests(nai);
11874 }
11875
11876 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -080011877 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
11878 if (nri.isMultilayerRequest()) {
11879 continue;
11880 }
11881 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090011882 if (!nr.isListen()) continue;
11883 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -080011884 nai.removeRequest(nr.requestId);
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090011885 callCallbackForRequest(nri, nai, CALLBACK_LOST, 0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090011886 }
11887 }
Chalard Jeancd397a22019-11-22 22:33:33 +090011888 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090011889
Chalard Jeancd397a22019-11-22 22:33:33 +090011890 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -080011891 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
11892 if (nri.isMultilayerRequest()) {
11893 continue;
11894 }
11895 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090011896 if (!nr.isListen()) continue;
11897 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
11898 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +090011899 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090011900 }
11901 }
11902 }
11903
Chalard Jean9fc27ea2019-12-02 15:34:05 +090011904 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +090011905 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +090011906 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -080011907 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +090011908 @Nullable public final NetworkRequest mOldNetworkRequest;
11909 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090011910 @Nullable public final NetworkAgentInfo mOldNetwork;
11911 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -080011912 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +090011913 @Nullable final NetworkRequest oldNetworkRequest,
11914 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +090011915 @Nullable final NetworkAgentInfo oldNetwork,
11916 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080011917 mNetworkRequestInfo = networkRequestInfo;
11918 mOldNetworkRequest = oldNetworkRequest;
11919 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090011920 mOldNetwork = oldNetwork;
11921 mNewNetwork = newNetwork;
11922 }
Chalard Jean49707572019-12-10 21:07:02 +090011923
11924 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +090011925 final NetworkRequest requestToShow = null != mNewNetworkRequest
11926 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
11927 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -080011928 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
11929 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +090011930 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +090011931 }
11932
Chalard Jean46a62372019-12-10 21:25:24 +090011933 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +090011934
Chalard Jeand8bea3b2019-12-02 18:59:27 +090011935 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +090011936 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090011937 }
11938
11939 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +090011940 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +090011941 // The code is never supposed to add two reassignments of the same request. Make
11942 // sure this stays true, but without imposing this expensive check on all
11943 // reassignments on all user devices.
11944 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -080011945 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +090011946 throw new IllegalStateException("Trying to reassign ["
11947 + reassignment + "] but already have ["
11948 + existing + "]");
11949 }
11950 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +090011951 }
Chalard Jean46a62372019-12-10 21:25:24 +090011952 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090011953 }
11954
Chalard Jean88b2f9e2019-12-03 14:43:57 +090011955 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +090011956 // the passed request.
11957 @Nullable
11958 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +090011959 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080011960 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +090011961 }
11962 return null;
11963 }
Chalard Jean49707572019-12-10 21:07:02 +090011964
11965 public String toString() {
11966 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
11967 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +090011968 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090011969 for (final RequestReassignment rr : getRequestReassignments()) {
11970 sj.add(rr.toString());
11971 }
11972 return sj.toString();
11973 }
11974
11975 public String debugString() {
11976 final StringBuilder sb = new StringBuilder();
11977 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +090011978 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090011979 for (final RequestReassignment rr : getRequestReassignments()) {
11980 sb.append("\n ").append(rr);
11981 }
11982 return sb.append("\n").toString();
11983 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +090011984 }
11985
Chalard Jean24344d72019-12-04 13:32:31 +090011986 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +090011987 @Nullable final NetworkRequest previousRequest,
11988 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +090011989 @Nullable final NetworkAgentInfo previousSatisfier,
11990 @Nullable final NetworkAgentInfo newSatisfier,
11991 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -080011992 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +090011993 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +090011994 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090011995 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +090011996 log(" accepting network in place of " + previousSatisfier.toShortString()
11997 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090011998 }
James Mattisa076c532020-12-02 14:12:41 -080011999 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090012000 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +090012001 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +090012002 // If this network switch can't be supported gracefully, the request is not
12003 // lingered. This allows letting go of the network sooner to reclaim some
12004 // performance on the new network, since the radio can't do both at the same
12005 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090012006 //
12007 // Also don't linger the request if the old network has been destroyed.
12008 // A destroyed network does not provide actual network connectivity, so
12009 // lingering it is not useful. In particular this ensures that a destroyed
12010 // network is outscored by its replacement,
12011 // then it is torn down immediately instead of being lingered, and any apps that
12012 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +090012013 previousSatisfier.lingerRequest(previousRequest.requestId, now);
12014 }
Chalard Jean24344d72019-12-04 13:32:31 +090012015 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +090012016 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090012017 }
junyulai0ac374f2020-12-14 18:41:52 +080012018
12019 // To prevent constantly CPU wake up for nascent timer, if a network comes up
12020 // and immediately satisfies a request then remove the timer. This will happen for
12021 // all networks except in the case of an underlying network for a VCN.
12022 if (newSatisfier.isNascent()) {
12023 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +080012024 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +080012025 }
12026
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012027 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -080012028 newSatisfier.unlingerRequest(newRequest.requestId);
12029 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +080012030 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -080012031 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090012032 }
Chalard Jeana8ac2302021-03-01 22:16:08 +090012033 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090012034 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090012035 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -080012036 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090012037 }
James Mattisa076c532020-12-02 14:12:41 -080012038 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090012039 }
James Mattisa076c532020-12-02 14:12:41 -080012040 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090012041 }
12042
James Mattisa076c532020-12-02 14:12:41 -080012043 /**
12044 * This function is triggered when something can affect what network should satisfy what
12045 * request, and it computes the network reassignment from the passed collection of requests to
12046 * network match to the one that the system should now have. That data is encoded in an
12047 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
12048 * satisfier.
12049 *
12050 * After the reassignment is computed, it is applied to the state objects.
12051 *
12052 * @param networkRequests the nri objects to evaluate for possible network reassignment
12053 * @return NetworkReassignment listing of proposed network assignment changes
12054 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090012055 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080012056 private NetworkReassignment computeNetworkReassignment(
12057 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090012058 final NetworkReassignment changes = new NetworkReassignment();
12059
Chalard Jeanc81d4c32021-04-07 17:06:19 +090012060 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090012061 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012062 forEachNetworkAgentInfo(nai -> nais.add(nai));
Chalard Jean857a1712019-12-10 21:08:07 +090012063
James Mattisa076c532020-12-02 14:12:41 -080012064 for (final NetworkRequestInfo nri : networkRequests) {
12065 // Non-multilayer listen requests can be ignored.
12066 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
12067 continue;
12068 }
12069 NetworkAgentInfo bestNetwork = null;
12070 NetworkRequest bestRequest = null;
12071 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090012072 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080012073 // Stop evaluating as the highest possible priority request is satisfied.
12074 if (null != bestNetwork) {
12075 bestRequest = req;
12076 break;
12077 }
12078 }
James Mattisd31bdfa2020-12-23 16:37:26 -080012079 if (null == bestNetwork && isDefaultBlocked(nri)) {
12080 // Remove default networking if disallowed for managed default requests.
12081 bestNetwork = mNoServiceNetwork;
12082 }
12083 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090012084 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090012085 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080012086 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090012087 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090012088 }
12089 return changes;
12090 }
12091
James Mattisa076c532020-12-02 14:12:41 -080012092 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
12093 return new HashSet<>(mNetworkRequests.values());
12094 }
12095
Paul Jensenc88b39b2015-06-16 14:27:36 -040012096 /**
James Mattisa076c532020-12-02 14:12:41 -080012097 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040012098 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040012099 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090012100 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080012101 rematchNetworksAndRequests(getNrisFromGlobalRequests());
12102 }
12103
12104 /**
12105 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
12106 * being disconnected.
12107 */
12108 private void rematchNetworksAndRequests(
12109 @NonNull final Set<NetworkRequestInfo> networkRequests) {
12110 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090012111 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090012112 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080012113 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090012114 final long computed = SystemClock.elapsedRealtime();
12115 applyNetworkReassignment(changes, start);
12116 final long applied = SystemClock.elapsedRealtime();
12117 issueNetworkNeeds();
12118 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090012119 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090012120 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
12121 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090012122 log(changes.debugString());
12123 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090012124 // Shorter form, only one line of log
12125 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
12126 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090012127 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090012128 }
Chalard Jean64520dc2019-12-04 19:55:32 +090012129
Chalard Jean1e4c2182023-10-06 18:45:53 +090012130 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
12131 @Nullable final NetworkAgentInfo nai2) {
12132 if (null == nai1) return null == nai2;
12133 if (null == nai2) return false;
12134 return nai1.linkProperties.getInterfaceName()
12135 .equals(nai2.linkProperties.getInterfaceName());
12136 }
12137
Chalard Jeand7f762d2019-12-10 19:01:29 +090012138 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090012139 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090012140 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090012141
12142 // Since most of the time there are only 0 or 1 background networks, it would probably
12143 // be more efficient to just use an ArrayList here. TODO : measure performance
12144 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
12145 for (final NetworkAgentInfo nai : nais) {
12146 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
12147 }
12148
Chalard Jeand7f762d2019-12-10 19:01:29 +090012149 // First, update the lists of satisfied requests in the network agents. This is necessary
12150 // because some code later depends on this state to be correct, most prominently computing
12151 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090012152 for (final NetworkReassignment.RequestReassignment event :
12153 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080012154 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
12155 event.mOldNetworkRequest, event.mNewNetworkRequest,
12156 event.mOldNetwork, event.mNewNetwork,
12157 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090012158 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090012159
James Mattise3ef1912020-12-20 11:09:58 -080012160 // Process default network changes if applicable.
12161 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090012162
Chalard Jean68eab722023-11-16 17:00:04 +090012163 // Update forwarding rules for the upstreams of local networks. Do this before sending
12164 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
12165 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
12166 // onAvailable so clients know what network the change is about. Store such changes in
12167 // an array that's only allocated if necessary (because it's almost never necessary).
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012168 final ArrayList<NetworkAgentInfo> localInfoChangedAgents = new ArrayList<>();
12169 forEachNetworkAgentInfo(nai -> {
12170 if (!nai.isLocalNetwork()) return; // return@forEach
Chalard Jean68eab722023-11-16 17:00:04 +090012171 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012172 if (null == nr) return; // return@forEach, no upstream for this local network
Chalard Jean68eab722023-11-16 17:00:04 +090012173 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
12174 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012175 if (null == change) return; // return@forEach, no change in upstreams for this network
Chalard Jean68eab722023-11-16 17:00:04 +090012176 final String fromIface = nai.linkProperties.getInterfaceName();
12177 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
12178 || change.mOldNetwork.isDestroyed()) {
12179 // There can be a change with the same interface name if the new network is the
12180 // replacement for the old network that was unregisteredAfterReplacement.
12181 try {
12182 if (null != change.mOldNetwork) {
12183 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
12184 change.mOldNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080012185 disableMulticastRouting(fromIface,
12186 change.mOldNetwork.linkProperties.getInterfaceName());
Chalard Jean68eab722023-11-16 17:00:04 +090012187 }
12188 // If the new upstream is already destroyed, there is no point in setting up
12189 // a forward (in fact, it might forward to the interface for some new network !)
12190 // Later when the upstream disconnects CS will try to remove the forward, which
12191 // is ignored with a benign log by RoutingCoordinatorService.
12192 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
12193 mRoutingCoordinatorService.addInterfaceForward(fromIface,
12194 change.mNewNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080012195 applyMulticastRoutingConfig(fromIface,
12196 change.mNewNetwork.linkProperties.getInterfaceName(),
12197 nai.localNetworkConfig);
Chalard Jean68eab722023-11-16 17:00:04 +090012198 }
12199 } catch (final RemoteException e) {
12200 loge("Can't update forwarding rules", e);
12201 }
12202 }
Chalard Jean68eab722023-11-16 17:00:04 +090012203 localInfoChangedAgents.add(nai);
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012204 });
Chalard Jean68eab722023-11-16 17:00:04 +090012205
Chalard Jeand8bea3b2019-12-02 18:59:27 +090012206 // Notify requested networks are available after the default net is switched, but
12207 // before LegacyTypeTracker sends legacy broadcasts
12208 for (final NetworkReassignment.RequestReassignment event :
12209 changes.getRequestReassignments()) {
12210 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080012211 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090012212 } else {
James Mattisa076c532020-12-02 14:12:41 -080012213 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090012214 CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090012215 }
12216 }
12217
junyulai0ac374f2020-12-14 18:41:52 +080012218 // Update the inactivity state before processing listen callbacks, because the background
12219 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090012220 // just yet though, because they have to be sent after the listens are processed to keep
12221 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080012222 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090012223 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080012224 // Rematching may have altered the inactivity state of some networks, so update all
12225 // inactivity timers. updateInactivityState reads the state from the network agent
12226 // and does nothing if the state has not changed : the source of truth is controlled
12227 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
12228 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080012229 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080012230 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090012231 }
12232 }
12233
Chalard Jeanb10ab412019-12-11 14:12:30 +090012234 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090012235 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090012236 // Process listen requests and update capabilities if the background state has
12237 // changed for this network. For consistency with previous behavior, send onLost
12238 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090012239 processNewlyLostListenRequests(nai);
12240 if (oldBackground != nai.isBackgroundNetwork()) {
12241 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090012242 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090012243 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090012244 }
12245
junyulai0ac374f2020-12-14 18:41:52 +080012246 for (final NetworkAgentInfo nai : inactiveNetworks) {
12247 // For nascent networks, if connecting with no foreground request, skip broadcasting
12248 // LOSING for backward compatibility. This is typical when mobile data connected while
12249 // wifi connected with mobile data always-on enabled.
12250 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090012251 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090012252 }
12253
Chalard Jean68eab722023-11-16 17:00:04 +090012254 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012255 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
12256 notifyNetworkCallbacks(nai, CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090012257 }
12258
James Mattise3ef1912020-12-20 11:09:58 -080012259 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090012260
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090012261 // Tear down all unneeded networks.
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012262 forEachNetworkAgentInfo(nai -> {
Chalard Jean0a8afda2019-11-07 19:05:18 +090012263 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080012264 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090012265 // This network has active linger timers and no requests, but is not
12266 // lingering. Linger it.
12267 //
12268 // One way (the only way?) this can happen if this network is unvalidated
12269 // and became unneeded due to another network improving its score to the
12270 // point where this network will no longer be able to satisfy any requests
12271 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080012272 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090012273 notifyNetworkLosing(nai, now);
12274 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090012275 } else {
Chalard Jean49707572019-12-10 21:07:02 +090012276 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090012277 teardownUnneededNetwork(nai);
12278 }
12279 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012280 });
Paul Jensen05e85ee2014-09-11 11:00:39 -040012281 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070012282
Chalard Jean62edfd82019-12-02 18:39:29 +090012283 /**
12284 * Apply a change in background state resulting from rematching networks with requests.
12285 *
12286 * During rematch, a network may change background states by starting to satisfy or stopping
12287 * to satisfy a foreground request. Listens don't count for this. When a network changes
12288 * background states, its capabilities need to be updated and callbacks fired for the
12289 * capability change.
12290 *
12291 * @param nai The network that changed background states
12292 */
12293 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
12294 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
12295 if (Objects.equals(nai.networkCapabilities, newNc)) return;
12296 updateNetworkPermissions(nai, newNc);
12297 nai.getAndSetNetworkCapabilities(newNc);
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090012298 notifyNetworkCallbacks(nai, CALLBACK_CAP_CHANGED);
Chalard Jean62edfd82019-12-02 18:39:29 +090012299 }
12300
Chalard Jeanf0344532019-11-19 19:23:38 +090012301 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080012302 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090012303 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090012304 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
12305 changes.getReassignment(mDefaultRequest);
12306 final NetworkAgentInfo oldDefaultNetwork =
12307 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
12308 final NetworkAgentInfo newDefaultNetwork =
12309 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080012310
Chalard Jean5b409c72021-02-04 13:12:59 +090012311 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090012312 // Maintain the illusion : since the legacy API only understands one network at a time,
12313 // if the default network changed, apps should see a disconnected broadcast for the
12314 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090012315 if (oldDefaultNetwork != null) {
12316 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
12317 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090012318 }
Chalard Jean5b409c72021-02-04 13:12:59 +090012319 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090012320 // The new default network can be newly null if and only if the old default
12321 // network doesn't satisfy the default request any more because it lost a
12322 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090012323 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080012324 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090012325 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090012326 }
12327 }
12328
Robert Greenwalte20f7a22014-04-18 15:25:25 -070012329 // Now that all the callbacks have been sent, send the legacy network broadcasts
12330 // as needed. This is necessary so that legacy requests correctly bind dns
12331 // requests to this network. The legacy users are listening for this broadcast
12332 // and will generally do a dns request so they can ensureRouteToHost and if
12333 // they do that before the callbacks happen they'll use the default network.
12334 //
12335 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
12336 // callbacks, but if apps can receive the broadcast before the callback, they still might
12337 // have an inconsistent view of networking.
12338 //
12339 // This *does* introduce a race where if the user uses the new api
12340 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
12341 // they may get old info. Reverse this after the old startUsing api is removed.
12342 // This is on top of the multiple intent sequencing referenced in the todo above.
12343 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090012344 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090012345 addNetworkToLegacyTypeTracker(nai);
12346 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080012347 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070012348 }
12349
Chalard Jean0354d8c2021-01-12 10:58:56 +090012350 private void issueNetworkNeeds() {
12351 ensureRunningOnConnectivityServiceThread();
12352 for (final NetworkOfferInfo noi : mNetworkOffers) {
12353 issueNetworkNeeds(noi);
12354 }
12355 }
12356
12357 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
12358 ensureRunningOnConnectivityServiceThread();
12359 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
12360 informOffer(nri, noi.offer, mNetworkRanker);
12361 }
12362 }
12363
12364 /**
12365 * Inform a NetworkOffer about any new situation of a request.
12366 *
12367 * This function handles updates to offers. A number of events may happen that require
12368 * updating the registrant for this offer about the situation :
12369 * • The offer itself was updated. This may lead the offer to no longer being able
12370 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
12371 * or conversely being strengthened enough to beat the satisfier (and therefore
12372 * start being needed)
12373 * • The network satisfying a request changed (including cases where the request
12374 * starts or stops being satisfied). The new network may be a stronger or weaker
12375 * match than the old one, possibly affecting whether the offer is needed.
12376 * • The network satisfying a request updated their score. This may lead the offer
12377 * to no longer be able to beat it if the current satisfier got better, or
12378 * conversely start being a good choice if the current satisfier got weaker.
12379 *
12380 * @param nri The request
12381 * @param offer The offer. This may be an updated offer.
12382 */
12383 private static void informOffer(@NonNull NetworkRequestInfo nri,
12384 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
12385 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
12386 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090012387
12388 // Multi-layer requests have a currently active request, the one being satisfied.
12389 // Since the system will try to bring up a better network than is currently satisfying
12390 // the request, NetworkProviders need to be told the offers matching the requests *above*
12391 // the currently satisfied one are needed, that the ones *below* the satisfied one are
12392 // not needed, and the offer is needed for the active request iff the offer can beat
12393 // the satisfier.
12394 // For non-multilayer requests, the logic above gracefully degenerates to only the
12395 // last case.
12396 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
12397 // providers that the offer is needed for this request, until the active request is found.
12398 // In a second phase, deal with the currently active request. In a third phase, inform
12399 // the providers that offer is unneeded for the remaining requests.
12400
12401 // First phase : inform providers of all requests above the active request.
12402 int i;
12403 for (i = 0; nri.mRequests.size() > i; ++i) {
12404 final NetworkRequest request = nri.mRequests.get(i);
12405 if (activeRequest == request) break; // Found the active request : go to phase 2
12406 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
12407 // Since this request is higher-priority than the one currently satisfied, if the
12408 // offer can satisfy it, the provider should try and bring up the network for sure ;
12409 // no need to even ask the ranker – an offer that can satisfy is always better than
12410 // no network. Hence tell the provider so unless it already knew.
12411 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
12412 offer.onNetworkNeeded(request);
12413 }
12414 }
12415
12416 // Second phase : deal with the active request (if any)
12417 if (null != activeRequest && activeRequest.isRequest()) {
12418 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000012419 // If an offer can satisfy the request, it is considered needed if it is currently
12420 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090012421 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000012422 && satisfier.factorySerialNumber == offer.providerId
12423 && activeRequest.canBeSatisfiedBy(offer.caps);
12424 final boolean newNeeded = currentlyServing
12425 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090012426 if (newNeeded != oldNeeded) {
12427 if (newNeeded) {
12428 offer.onNetworkNeeded(activeRequest);
12429 } else {
12430 // The offer used to be able to beat the satisfier. Now it can't.
12431 offer.onNetworkUnneeded(activeRequest);
12432 }
12433 }
12434 }
12435
12436 // Third phase : inform the providers that the offer isn't needed for any request
12437 // below the active one.
12438 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
12439 final NetworkRequest request = nri.mRequests.get(i);
12440 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
12441 // Since this request is lower-priority than the one currently satisfied, if the
12442 // offer can satisfy it, the provider should not try and bring up the network.
12443 // Hence tell the provider so unless it already knew.
12444 if (offer.neededFor(request)) {
12445 offer.onNetworkUnneeded(request);
12446 }
12447 }
12448 }
12449
Chalard Jean61c79252019-11-07 23:07:32 +090012450 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
12451 for (int i = 0; i < nai.numNetworkRequests(); i++) {
12452 NetworkRequest nr = nai.requestAt(i);
12453 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
12454 // legacy type tracker filters out repeat adds
12455 mLegacyTypeTracker.add(nr.legacyType, nai);
12456 }
12457 }
12458
12459 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090012460 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090012461 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
12462 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
12463 if (nai.isVPN()) {
12464 mLegacyTypeTracker.add(TYPE_VPN, nai);
12465 }
12466 }
12467
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090012468 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040012469 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090012470 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090012471 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040012472 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090012473 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040012474
Chalard Jean254bd162022-08-25 13:04:51 +090012475 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040012476 // Don't repeat publish.
12477 if (newInetCondition == mDefaultInetConditionPublished) return;
12478
12479 mDefaultInetConditionPublished = newInetCondition;
12480 sendInetConditionBroadcast(nai.networkInfo);
12481 }
12482
Chalard Jeand61375d2020-01-14 22:46:36 +090012483 @NonNull
12484 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
12485 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090012486 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090012487 final boolean suspended =
12488 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
12489 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
12490 // Only override the state with SUSPENDED if the network is currently in CONNECTED
12491 // state. This is because the network could have been suspended before connecting,
12492 // or it could be disconnecting while being suspended, and in both these cases
12493 // the state should not be overridden. Note that the only detailed state that
12494 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
12495 // worry about multiple different substates of CONNECTED.
12496 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
12497 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080012498 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
12499 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
12500 // network agent is created, then goes to suspended, then goes out of suspended without
12501 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090012502 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080012503 ? NetworkInfo.DetailedState.CONNECTED
12504 : NetworkInfo.DetailedState.CONNECTING,
12505 info.getReason(),
12506 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090012507 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090012508 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090012509 return newInfo;
12510 }
12511
12512 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
12513 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
12514
Erik Kline99f301b2017-02-15 19:59:17 +090012515 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070012516 NetworkInfo oldInfo = null;
12517 synchronized (networkAgent) {
12518 oldInfo = networkAgent.networkInfo;
12519 networkAgent.networkInfo = newInfo;
12520 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070012521
Robert Greenwalte20f7a22014-04-18 15:25:25 -070012522 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090012523 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
12524 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070012525 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070012526
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090012527 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090012528 // A network that has just connected has zero requests and is thus a foreground network.
12529 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
12530
Luke Huangfdd11f82019-04-09 18:41:49 +080012531 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090012532
12533 networkAgent.setCreated();
12534
12535 // If the network is created immediately on register, then apply the LinkProperties now.
12536 // Otherwise, this is done further down when the network goes into connected state.
12537 // Applying the LinkProperties means that the network is ready to carry traffic -
12538 // interfaces and routing rules have been added, DNS servers programmed, etc.
12539 // For VPNs, this must be done before the capabilities are updated, because as soon as
12540 // that happens, UIDs are routed to the network.
Junyu Lai91ef9d32025-02-26 17:33:27 +080012541 if (shouldCreateNetworksImmediately(networkAgent.getCapsNoCopy())) {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090012542 applyInitialLinkProperties(networkAgent);
12543 }
12544
12545 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
12546 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090012547 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090012548 // Initialize the network's capabilities to their starting values according to the
12549 // underlying networks. This ensures that the capabilities are correct before
12550 // anything happens to the network.
12551 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090012552 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080012553 networkAgent.onNetworkCreated();
Tommy Webba0dad0a2023-02-20 14:10:55 -050012554 updateDisallowedUidsForNetwork(networkAgent);
Chalard Jeande665262022-02-25 16:12:12 +090012555 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080012556 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010012557 }
12558
Chalard Jean254bd162022-08-25 13:04:51 +090012559 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
12560 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010012561
lucaslin45e639b2019-04-03 17:09:28 +080012562 // NetworkCapabilities need to be set before sending the private DNS config to
12563 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090012564 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
12565
Erik Kline9a62f012018-03-21 07:18:33 -070012566 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Junyu Lai91ef9d32025-02-26 17:33:27 +080012567 if (!shouldCreateNetworksImmediately(networkAgent.getCapsNoCopy())) {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090012568 applyInitialLinkProperties(networkAgent);
12569 } else {
12570 // The network was created when the agent registered, and the LinkProperties are
12571 // already up-to-date. However, updateLinkProperties also makes some changes only
12572 // when the network connects. Apply those changes here. On T and below these are
12573 // handled by the applyInitialLinkProperties call just above.
12574 // TODO: stop relying on updateLinkProperties(..., null) to do this.
12575 // If something depends on both LinkProperties and connected state, it should be in
12576 // this method as well.
12577 networkAgent.clatd.update();
12578 updateProxy(networkAgent.linkProperties, null);
12579 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090012580
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010012581 // If a rate limit has been configured and is applicable to this network (network
12582 // provides internet connectivity), apply it. The tc police filter cannot be attached
12583 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090012584 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010012585 // Note: in case of a system server crash, the NetworkController constructor in netd
12586 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
12587 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
12588 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12589 mIngressRateLimit);
12590 }
12591
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090012592 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
12593 // command must be sent after updating LinkProperties to maximize chances of
12594 // NetworkMonitor seeing the correct LinkProperties when starting.
12595 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090012596 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090012597 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090012598 }
Chalard Jeand4900722022-02-06 12:25:38 +090012599 final NetworkMonitorParameters params = new NetworkMonitorParameters();
12600 params.networkAgentConfig = networkAgent.networkAgentConfig;
12601 params.networkCapabilities = networkAgent.networkCapabilities;
12602 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
12603 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090012604 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
12605 // newer callback even before T. However getInterfaceVersion is a synchronized binder
12606 // call that would cause a Log.wtf to be emitted from the system_server process, and
12607 // in the absence of a satisfactory, scalable solution which follows an easy/standard
12608 // process to check the interface version, just use an SDK check. NetworkStack will
12609 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090012610 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090012611 networkAgent.networkMonitor().notifyNetworkConnected(params);
12612 } else {
12613 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
12614 params.networkCapabilities);
12615 }
Chalard Jean0f141332023-06-05 19:26:17 +090012616 final long evaluationDelay;
12617 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
12618 // If the network is anything other than pure wifi, use the default timeout.
12619 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
12620 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
12621 // If the network is explicitly selected, use the default timeout because it's
12622 // shorter and the user is likely staring at the screen expecting it to validate
12623 // right away.
12624 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
12625 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
12626 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
12627 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
12628 } else {
12629 // It's wifi, automatically connected, and bad wifi is preferred : use the
12630 // longer timeout to avoid the device switching to captive portals with bad
12631 // signal or very slow response.
12632 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
12633 }
12634 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090012635
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090012636 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
12637 // be communicated to a particular NetworkAgent depends only on the network's immutable,
12638 // capabilities, so it only needs to be done once on initial connect, not every time the
12639 // network's capabilities change. Note that we do this before rematching the network,
12640 // so we could decide to tear it down immediately afterwards. That's fine though - on
12641 // disconnection NetworkAgents should stop any signal strength monitoring they have been
12642 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090012643 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090012644
junyulai0ac374f2020-12-14 18:41:52 +080012645 // Before first rematching networks, put an inactivity timer without any request, this
12646 // allows {@code updateInactivityState} to update the state accordingly and prevent
12647 // tearing down for any {@code unneeded} evaluation in this period.
12648 // Note that the timer will not be rescheduled since the expiry time is
12649 // fixed after connection regardless of the network satisfying other requests or not.
12650 // But it will be removed as soon as the network satisfies a request for the first time.
12651 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
12652 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080012653 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080012654
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012655 if (mTrackMultiNetworkActivities) {
12656 // Start tracking activity of this network.
12657 // This must be called before rematchAllNetworksAndRequests since the network
12658 // should be tracked when the network becomes the default network.
12659 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
12660 // can be triggered later if this network becomes the default network.
12661 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
12662 }
12663
Paul Jensen05e85ee2014-09-11 11:00:39 -040012664 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090012665 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090012666
12667 // This has to happen after matching the requests, because callbacks are just requests.
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090012668 notifyNetworkCallbacks(networkAgent, CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070012669 } else if (state == NetworkInfo.State.DISCONNECTED) {
Chalard Jean9fdc9882025-03-21 10:13:47 +090012670 if (!mQueueNetworkAgentEventsInSystemServer) {
12671 networkAgent.disconnect();
12672 }
Paul Jensen8b5fc622014-05-07 15:27:40 -040012673 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000012674 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040012675 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090012676 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000012677 if (networkAgent.isVPN()) {
12678 // As the active or bound network changes for apps, broadcast the default proxy, as
12679 // apps may need to update their proxy data. This is called after disconnecting from
12680 // VPN to make sure we do not broadcast the old proxy data.
12681 // TODO(b/122649188): send the broadcast only to VPN users.
12682 mProxyTracker.sendProxyBroadcast();
12683 }
Chalard Jean254bd162022-08-25 13:04:51 +090012684 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
12685 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070012686 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070012687 }
12688 }
12689
Chalard Jean28018572020-12-21 18:36:52 +090012690 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090012691 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
12692 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090012693 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070012694 }
12695
Erik Kline99f301b2017-02-15 19:59:17 +090012696 // Notify only this one new request of the current state. Transfer all the
12697 // current state by calling NetworkCapabilities and LinkProperties callbacks
12698 // so that callers can be guaranteed to have as close to atomicity in state
12699 // transfer as can be supported by this current API.
12700 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070012701 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090012702 if (nri.mPendingIntent != null) {
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090012703 sendPendingIntentForRequest(nri, nai, CALLBACK_AVAILABLE);
Erik Kline99f301b2017-02-15 19:59:17 +090012704 // Attempt no subsequent state pushes where intents are involved.
12705 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080012706 }
Erik Kline99f301b2017-02-15 19:59:17 +090012707
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +090012708 callCallbackForRequest(nri, nai, CALLBACK_AVAILABLE, getBlockedState(nai, nri.mAsUid));
junyulaif2c67e42018-08-07 19:50:45 +080012709 }
12710
Chalard Jean8fd82ae2019-12-04 18:49:18 +090012711 // Notify the requests on this NAI that the network is now lingered.
12712 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080012713 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090012714 notifyNetworkCallbacks(nai, CALLBACK_LOSING, lingerTime);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090012715 }
12716
Motomu Utsumicfd5a512024-05-27 02:12:43 +000012717 private int getPermissionBlockedState(final int uid, final int reasons) {
12718 // Before V, the blocked reasons come from NPMS, and that code already behaves as if the
12719 // change was disabled: apps without the internet permission will never be told they are
12720 // blocked.
12721 if (!mDeps.isAtLeastV()) return reasons;
12722
12723 if (hasInternetPermission(uid)) return reasons;
12724
12725 return mDeps.isChangeEnabled(NETWORK_BLOCKED_WITHOUT_INTERNET_PERMISSION, uid)
12726 ? reasons | BLOCKED_REASON_NETWORK_RESTRICTED
12727 : BLOCKED_REASON_NONE;
12728 }
12729
12730 private int getBlockedState(int uid, int reasons, boolean metered, boolean vpnBlocked) {
12731 reasons = getPermissionBlockedState(uid, reasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090012732 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
12733 return vpnBlocked
12734 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
12735 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
12736 }
12737
Remi NGUYEN VANa65af5f2024-07-08 17:23:10 +090012738 private int getBlockedState(@NonNull NetworkAgentInfo nai, int uid) {
12739 final boolean metered = nai.networkCapabilities.isMetered();
12740 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
12741 final int blockedReasons = mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE);
12742 return getBlockedState(uid, blockedReasons, metered, vpnBlocked);
12743 }
12744
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090012745 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
12746 if (blockedReasons == BLOCKED_REASON_NONE) {
12747 mUidBlockedReasons.delete(uid);
12748 } else {
12749 mUidBlockedReasons.put(uid, blockedReasons);
12750 }
12751 }
12752
junyulaif2c67e42018-08-07 19:50:45 +080012753 /**
12754 * Notify of the blocked state apps with a registered callback matching a given NAI.
12755 *
12756 * Unlike other callbacks, blocked status is different between each individual uid. So for
12757 * any given nai, all requests need to be considered according to the uid who filed it.
12758 *
12759 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090012760 * @param oldMetered True if the previous network capabilities were metered.
12761 * @param newMetered True if the current network capabilities are metered.
12762 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
12763 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080012764 */
12765 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000012766 boolean newMetered, List<UidRange> oldBlockedUidRanges,
12767 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080012768
12769 for (int i = 0; i < nai.numNetworkRequests(); i++) {
12770 NetworkRequest nr = nai.requestAt(i);
12771 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090012772
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090012773 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
12774 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
12775 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012776 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090012777 : oldVpnBlocked;
12778
Motomu Utsumicfd5a512024-05-27 02:12:43 +000012779 final int oldBlockedState = getBlockedState(
12780 nri.mAsUid, blockedReasons, oldMetered, oldVpnBlocked);
12781 final int newBlockedState = getBlockedState(
12782 nri.mAsUid, blockedReasons, newMetered, newVpnBlocked);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090012783 if (oldBlockedState != newBlockedState) {
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090012784 callCallbackForRequest(nri, nai, CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090012785 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080012786 }
12787 }
12788 }
12789
12790 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000012791 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080012792 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000012793 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080012794 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090012795 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012796 forEachNetworkAgentInfo(nai -> {
junyulaif2c67e42018-08-07 19:50:45 +080012797 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090012798 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000012799
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090012800 final int oldBlockedState = getBlockedState(
Motomu Utsumicfd5a512024-05-27 02:12:43 +000012801 uid, mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
12802 final int newBlockedState =
12803 getBlockedState(uid, blockedReasons, metered, vpnBlocked);
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012804 if (oldBlockedState == newBlockedState) return; // return@forEach
junyulaif2c67e42018-08-07 19:50:45 +080012805 for (int i = 0; i < nai.numNetworkRequests(); i++) {
12806 NetworkRequest nr = nai.requestAt(i);
12807 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012808 if (nri != null && nri.mAsUid == uid) {
Remi NGUYEN VANbaf7c112024-06-11 20:29:15 +090012809 callCallbackForRequest(nri, nai, CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090012810 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080012811 }
12812 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012813 });
Robert Greenwaltf99b8392014-03-26 16:47:06 -070012814 }
12815
Chalard Jean3a3f5f22019-04-10 23:07:55 +090012816 @VisibleForTesting
12817 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090012818 // The NetworkInfo we actually send out has no bearing on the real
12819 // state of affairs. For example, if the default connection is mobile,
12820 // and a request for HIPRI has just gone away, we need to pretend that
12821 // HIPRI has just disconnected. So we need to set the type to HIPRI and
12822 // the state to DISCONNECTED, even though the network is of type MOBILE
12823 // and is still connected.
12824 NetworkInfo info = new NetworkInfo(nai.networkInfo);
12825 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090012826 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070012827 if (state != DetailedState.DISCONNECTED) {
12828 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090012829 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070012830 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070012831 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070012832 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
12833 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
12834 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
12835 if (info.isFailover()) {
12836 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
12837 nai.networkInfo.setFailover(false);
12838 }
12839 if (info.getReason() != null) {
12840 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
12841 }
12842 if (info.getExtraInfo() != null) {
12843 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
12844 }
12845 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090012846 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080012847 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070012848 if (newDefaultAgent != null) {
12849 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
12850 newDefaultAgent.networkInfo);
12851 } else {
12852 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
12853 }
12854 }
12855 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
12856 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090012857 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070012858 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090012859 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070012860 }
12861 }
12862 }
12863
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090012864 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090012865 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090012866 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090012867 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090012868 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090012869 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
12870 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070012871 NetworkRequestInfo nri = mNetworkRequests.get(nr);
12872 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080012873 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090012874 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080012875 } else {
12876 sendPendingIntentForRequest(nri, networkAgent, notifyType);
12877 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070012878 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070012879 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070012880
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090012881 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
12882 notifyNetworkCallbacks(networkAgent, notifyType, 0);
12883 }
12884
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080012885 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090012886 * Returns the list of all interfaces that could be used by network traffic that does not
12887 * explicitly specify a network. This includes the default network, but also all VPNs that are
12888 * currently connected.
12889 *
12890 * Must be called on the handler thread.
12891 */
junyulaie7c7d2a2021-01-26 15:29:15 +080012892 @NonNull
12893 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080012894 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080012895 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080012896 final Set<Integer> activeNetIds = new ArraySet<>();
12897 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
12898 if (nri.isBeingSatisfied()) {
12899 activeNetIds.add(nri.getSatisfier().network().netId);
12900 }
12901 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012902 forEachNetworkAgentInfo(nai -> {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090012903 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090012904 defaultNetworks.add(nai.network);
12905 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +090012906 });
junyulaie7c7d2a2021-01-26 15:29:15 +080012907 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090012908 }
12909
12910 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090012911 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
12912 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080012913 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080012914 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080012915 ensureRunningOnConnectivityServiceThread();
12916 String activeIface = null;
12917 LinkProperties activeLinkProperties = getActiveLinkProperties();
12918 if (activeLinkProperties != null) {
12919 activeIface = activeLinkProperties.getInterfaceName();
12920 }
Benedict Wong9308cd32019-06-12 17:46:31 +000012921
junyulai2050bed2021-01-23 09:46:34 +080012922 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080012923 try {
junyulaide41fc22021-01-22 22:46:01 +080012924 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090012925 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080012926 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
12927 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080012928 } catch (Exception ignored) {
12929 }
12930 }
12931
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070012932 @Override
Udam Sainicd645462016-01-04 12:16:14 -080012933 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080012934 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090012935 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090012936 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010012937
12938 if (!TextUtils.isEmpty(settingUrl)) {
12939 return settingUrl;
12940 }
12941
12942 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012943 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010012944 if (!TextUtils.isEmpty(settingUrl)) {
12945 return settingUrl;
12946 }
12947
12948 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080012949 }
12950
12951 @Override
junyulai070f9ff2019-01-16 20:23:34 +080012952 public void startNattKeepalive(Network network, int intervalSeconds,
12953 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090012954 enforceKeepalivePermission();
12955 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080012956 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000012957 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
12958 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000012959 // false and set the underpinned network to null because there is no way and no
12960 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
12961 // deprecated method.
12962 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090012963 }
12964
12965 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080012966 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080012967 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000012968 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070012969 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080012970 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070012971 mKeepaliveTracker.startNattKeepalive(
12972 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000012973 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
12974 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070012975 } finally {
12976 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
12977 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080012978 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
12979 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070012980 }
12981 }
junyulaid05a1922019-01-15 11:32:44 +080012982 }
12983
12984 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080012985 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080012986 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070012987 try {
12988 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080012989 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070012990 mKeepaliveTracker.startTcpKeepalive(
12991 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
12992 } finally {
12993 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
12994 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080012995 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
12996 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070012997 }
12998 }
junyulai0835a1e2019-01-08 20:04:33 +080012999 }
13000
13001 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090013002 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090013003 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090013004 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
13005 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090013006 }
13007
13008 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090013009 public int[] getSupportedKeepalives() {
13010 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
13011 // Backwards compatibility with CTS 13
13012 android.Manifest.permission.QUERY_ALL_PACKAGES);
13013
13014 return BinderUtils.withCleanCallingIdentity(() ->
13015 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
13016 }
13017
13018 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070013019 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080013020 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070013021
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080013022 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080013023 final long token = Binder.clearCallingIdentity();
13024 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080013025 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
13026 UserHandle.getUserHandleForUid(uid))) {
13027 return;
13028 }
13029
Heemin Seogdb8489d2019-06-12 09:21:44 -070013030 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
13031 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080013032
13033 // Turn airplane mode off
13034 setAirplaneMode(false);
13035
13036 // restore private DNS settings to default mode (opportunistic)
13037 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
13038 UserHandle.getUserHandleForUid(uid))) {
13039 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
13040 PRIVATE_DNS_MODE_OPPORTUNISTIC);
13041 }
13042
13043 Settings.Global.putString(mContext.getContentResolver(),
13044 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080013045 } finally {
13046 Binder.restoreCallingIdentity(token);
13047 }
Stuart Scottd5463642015-04-02 18:00:02 -070013048 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040013049
Ricky Wai7097cc92018-01-23 04:09:45 +000013050 @Override
13051 public byte[] getNetworkWatchlistConfigHash() {
13052 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
13053 if (nwm == null) {
13054 loge("Unable to get NetworkWatchlistManager");
13055 return null;
13056 }
13057 // Redirect it to network watchlist service to access watchlist file and calculate hash.
13058 return nwm.getWatchlistConfigHash();
13059 }
13060
Hugo Benichibe0c7652016-05-31 16:28:06 +090013061 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090013062 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080013063 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090013064 }
Hugo Benichif4210292017-04-21 15:07:12 +090013065
13066 private static boolean toBool(int encodedBoolean) {
13067 return encodedBoolean != 0; // Only 0 means false.
13068 }
13069
13070 private static int encodeBool(boolean b) {
13071 return b ? 1 : 0;
13072 }
mswest4632928412018-03-12 10:34:34 -070013073
13074 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080013075 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
13076 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
13077 @NonNull String[] args) {
13078 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
13079 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070013080 }
13081
Chiachang Wang77ae8a02020-10-12 15:20:07 +080013082 private class ShellCmd extends BasicShellCommandHandler {
Suprabh Shukla22ea1662024-02-08 16:06:01 -080013083
13084 private Boolean parseBooleanArgument(final String arg) {
13085 if ("true".equals(arg)) {
13086 return true;
13087 } else if ("false".equals(arg)) {
13088 return false;
13089 } else {
13090 getOutPrintWriter().println("Invalid boolean argument: " + arg);
13091 return null;
13092 }
13093 }
13094
13095 private Integer parseIntegerArgument(final String arg) {
13096 try {
13097 return Integer.valueOf(arg);
13098 } catch (NumberFormatException ne) {
13099 getOutPrintWriter().println("Invalid integer argument: " + arg);
13100 return null;
13101 }
13102 }
13103
mswest4632928412018-03-12 10:34:34 -070013104 @Override
13105 public int onCommand(String cmd) {
13106 if (cmd == null) {
13107 return handleDefaultCommands(cmd);
13108 }
13109 final PrintWriter pw = getOutPrintWriter();
13110 try {
13111 switch (cmd) {
13112 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090013113 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
13114 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070013115 final String action = getNextArg();
13116 if ("enable".equals(action)) {
13117 setAirplaneMode(true);
13118 return 0;
13119 } else if ("disable".equals(action)) {
13120 setAirplaneMode(false);
13121 return 0;
13122 } else if (action == null) {
13123 final ContentResolver cr = mContext.getContentResolver();
13124 final int enabled = Settings.Global.getInt(cr,
13125 Settings.Global.AIRPLANE_MODE_ON);
13126 pw.println(enabled == 0 ? "disabled" : "enabled");
13127 return 0;
13128 } else {
13129 onHelp();
13130 return -1;
13131 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013132 case "set-chain3-enabled": {
13133 final Boolean enabled = parseBooleanArgument(getNextArg());
13134 if (null == enabled) {
13135 onHelp();
13136 return -1;
13137 }
13138 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
13139 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
13140 enabled);
13141 return 0;
13142 }
13143 case "get-chain3-enabled": {
13144 final boolean chainEnabled = getFirewallChainEnabled(
13145 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
13146 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
13147 return 0;
13148 }
13149 case "set-package-networking-enabled": {
13150 final Boolean enabled = parseBooleanArgument(getNextArg());
13151 final String packageName = getNextArg();
13152 if (null == enabled || null == packageName) {
13153 onHelp();
13154 return -1;
13155 }
13156 // Throws NameNotFound if the package doesn't exist.
13157 final int appId = setPackageFirewallRule(
13158 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
13159 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
13160 final String msg = (enabled ? "Enabled" : "Disabled")
13161 + " networking for " + packageName + ", appId " + appId;
13162 Log.i(TAG, msg);
13163 pw.println(msg);
13164 return 0;
13165 }
13166 case "get-package-networking-enabled": {
Motomu Utsumia1a00342024-06-13 09:29:47 +000013167 if (!mDeps.isAtLeastT()) {
13168 throw new UnsupportedOperationException(
13169 "This command is not supported on T-");
13170 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013171 final String packageName = getNextArg();
13172 final int rule = getPackageFirewallRule(
13173 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
13174 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
13175 pw.println(packageName + ":" + "allow");
13176 } else if (FIREWALL_RULE_DENY == rule) {
13177 pw.println(packageName + ":" + "deny");
13178 } else {
13179 throw new IllegalStateException("Unknown rule " + rule + " for package "
13180 + packageName);
13181 }
13182 return 0;
13183 }
Suprabh Shukla22ea1662024-02-08 16:06:01 -080013184 case "set-background-networking-enabled-for-uid": {
13185 final Integer uid = parseIntegerArgument(getNextArg());
13186 final Boolean enabled = parseBooleanArgument(getNextArg());
13187 if (null == enabled || null == uid) {
13188 onHelp();
13189 return -1;
13190 }
13191 final int rule = enabled ? FIREWALL_RULE_ALLOW : FIREWALL_RULE_DEFAULT;
13192 setUidFirewallRule(FIREWALL_CHAIN_BACKGROUND, uid, rule);
13193 final String msg = (enabled ? "Enabled" : "Disabled")
13194 + " background networking for uid " + uid;
13195 Log.i(TAG, msg);
13196 pw.println(msg);
13197 return 0;
13198 }
13199 case "get-background-networking-enabled-for-uid": {
Motomu Utsumia1a00342024-06-13 09:29:47 +000013200 if (!mDeps.isAtLeastT()) {
13201 throw new UnsupportedOperationException(
13202 "This command is not supported on T-");
13203 }
Suprabh Shukla22ea1662024-02-08 16:06:01 -080013204 final Integer uid = parseIntegerArgument(getNextArg());
13205 if (null == uid) {
13206 onHelp();
13207 return -1;
13208 }
13209 final int rule = getUidFirewallRule(FIREWALL_CHAIN_BACKGROUND, uid);
13210 if (FIREWALL_RULE_ALLOW == rule) {
13211 pw.println(uid + ": allow");
13212 } else if (FIREWALL_RULE_DENY == rule || FIREWALL_RULE_DEFAULT == rule) {
13213 pw.println(uid + ": deny");
13214 } else {
13215 throw new IllegalStateException(
13216 "Unknown rule " + rule + " for uid " + uid);
13217 }
13218 return 0;
13219 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090013220 case "reevaluate":
13221 // Usage : adb shell cmd connectivity reevaluate <netId>
13222 // If netId is omitted, then reevaluate the default network
13223 final String netId = getNextArg();
13224 final NetworkAgentInfo nai;
13225 if (null == netId) {
13226 // Note that the command is running on the wrong thread to call this,
13227 // so this could in principle return stale data. But it can't crash.
13228 nai = getDefaultNetwork();
13229 } else {
13230 // If netId can't be parsed, this throws NumberFormatException, which
13231 // is passed back to adb who prints it.
13232 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
13233 }
13234 if (null == nai) {
13235 pw.println("Unknown network (net ID not found or no default network)");
13236 return 0;
13237 }
13238 Log.d(TAG, "Reevaluating network " + nai.network);
13239 reportNetworkConnectivity(nai.network, !nai.isValidated());
13240 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080013241 case "bpf-get-cgroup-program-id": {
13242 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
13243 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
13244 // for more detail.
13245 // If type can't be parsed, this throws NumberFormatException, which
13246 // is passed back to adb who prints it.
13247 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000013248 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080013249 pw.println(ret);
13250 return 0;
13251 }
mswest4632928412018-03-12 10:34:34 -070013252 default:
13253 return handleDefaultCommands(cmd);
13254 }
13255 } catch (Exception e) {
13256 pw.println(e);
13257 }
13258 return -1;
13259 }
13260
13261 @Override
13262 public void onHelp() {
13263 PrintWriter pw = getOutPrintWriter();
13264 pw.println("Connectivity service commands:");
13265 pw.println(" help");
13266 pw.println(" Print this help text.");
13267 pw.println(" airplane-mode [enable|disable]");
13268 pw.println(" Turn airplane mode on or off.");
13269 pw.println(" airplane-mode");
13270 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013271 pw.println(" set-chain3-enabled [true|false]");
13272 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
13273 pw.println(" get-chain3-enabled");
13274 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
13275 pw.println(" set-package-networking-enabled [true|false] [package name]");
13276 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
13277 + " no effect if the chain is disabled.");
13278 pw.println(" get-package-networking-enabled [package name]");
13279 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
Suprabh Shukla22ea1662024-02-08 16:06:01 -080013280 pw.println(" set-background-networking-enabled-for-uid [uid] [true|false]");
13281 pw.println(" Set the allow bit in FIREWALL_CHAIN_BACKGROUND for the given uid.");
13282 pw.println(" get-background-networking-enabled-for-uid [uid]");
13283 pw.println(" Get the allow bit in FIREWALL_CHAIN_BACKGROUND for the given uid.");
mswest4632928412018-03-12 10:34:34 -070013284 }
13285 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070013286
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090013287 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090013288 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
13289 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
13290 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080013291 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070013292 }
13293
Lorenzo Colittifd89cf52025-03-18 13:13:45 +090013294 private boolean isVpnServiceVpn(NetworkAgentInfo nai) {
13295 final int vpnType = getVpnType(nai);
13296 return vpnType == VpnManager.TYPE_VPN_SERVICE || vpnType == VpnManager.TYPE_VPN_OEM_SERVICE;
13297 }
13298
13299 private boolean isLegacyVpn(NetworkAgentInfo nai) {
13300 final int vpnType = getVpnType(nai);
13301 return vpnType == VpnManager.TYPE_VPN_LEGACY || vpnType == VpnManager.TYPE_VPN_OEM_LEGACY;
13302 }
13303
13304 private boolean vpnSupportsInterfaceFiltering(NetworkAgentInfo vpn) {
13305 final int vpnType = getVpnType(vpn);
13306 return vpnType != VpnManager.TYPE_VPN_LEGACY
13307 && vpnType != VpnManager.TYPE_VPN_OEM
13308 && vpnType != VpnManager.TYPE_VPN_OEM_LEGACY;
13309 }
13310
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090013311 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
13312 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090013313 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
13314 final TransportInfo newInfo = nc.getTransportInfo();
13315 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
13316 return;
13317 }
13318 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090013319 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090013320 }
13321 }
13322
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070013323 /**
13324 * @param connectionInfo the connection to resolve.
13325 * @return {@code uid} if the connection is found and the app has permission to observe it
13326 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
13327 * connection is not found.
13328 */
13329 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070013330 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
13331 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
13332 }
13333
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090013334 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070013335 connectionInfo.local, connectionInfo.remote);
13336
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090013337 if (uid == INVALID_UID) return uid; // Not found.
13338
13339 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
13340 // VPN, if any, that applies to the UID that owns the connection.
Junyu Lai71b51532024-02-01 10:39:01 +080013341 if (hasNetworkStackPermission()) return uid;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090013342
13343 final NetworkAgentInfo vpn = getVpnForUid(uid);
Lorenzo Colittifd89cf52025-03-18 13:13:45 +090013344 if (vpn == null || !isVpnServiceVpn(vpn)
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090013345 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070013346 return INVALID_UID;
13347 }
13348
13349 return uid;
13350 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000013351
Benedict Wong493e04b2018-11-09 14:45:34 -080013352 /**
13353 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
13354 *
13355 * <p>The TestNetworkService must be run in the system server due to TUN creation.
13356 */
13357 @Override
13358 public IBinder startOrGetTestNetworkService() {
13359 synchronized (mTNSLock) {
13360 TestNetworkService.enforceTestNetworkPermissions(mContext);
13361
13362 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080013363 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080013364 }
13365
13366 return mTNS;
13367 }
13368 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080013369
Cody Kesting73708bf2019-12-18 10:57:50 -080013370 /**
13371 * Handler used for managing all Connectivity Diagnostics related functions.
13372 *
13373 * @see android.net.ConnectivityDiagnosticsManager
13374 *
13375 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
13376 */
13377 @VisibleForTesting
13378 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080013379 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
13380
Cody Kesting73708bf2019-12-18 10:57:50 -080013381 /**
13382 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
13383 * android.net.ConnectivityDiagnosticsManager}.
13384 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
13385 * NetworkRequestInfo to be registered
13386 */
13387 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
13388
13389 /**
13390 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
13391 * android.net.ConnectivityDiagnosticsManager}.
13392 * obj = the IConnectivityDiagnosticsCallback to be unregistered
13393 * arg1 = the uid of the caller
13394 */
13395 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
13396
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013397 /**
13398 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090013399 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013400 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
13401 * NetworkMonitor.
13402 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013403 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090013404 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013405
Cody Kestingb12ad4c2020-01-06 16:55:35 -080013406 /**
13407 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
13408 * been detected on the network.
13409 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
13410 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
13411 * arg2 = NetID.
13412 * data = PersistableBundle of extras passed from NetworkMonitor.
13413 */
13414 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
13415
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080013416 /**
13417 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
13418 * the platform. This event will invoke {@link
13419 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
13420 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070013421 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080013422 */
13423 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
13424
Cody Kesting73708bf2019-12-18 10:57:50 -080013425 private ConnectivityDiagnosticsHandler(Looper looper) {
13426 super(looper);
13427 }
13428
13429 @Override
13430 public void handleMessage(Message msg) {
13431 switch (msg.what) {
13432 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
13433 handleRegisterConnectivityDiagnosticsCallback(
13434 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
13435 break;
13436 }
13437 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
13438 handleUnregisterConnectivityDiagnosticsCallback(
13439 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
13440 break;
13441 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090013442 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013443 final ConnectivityReportEvent reportEvent =
13444 (ConnectivityReportEvent) msg.obj;
13445
Aaron Huang959d3642021-01-21 15:47:41 +080013446 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013447 break;
13448 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080013449 case EVENT_DATA_STALL_SUSPECTED: {
13450 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080013451 final Pair<Long, PersistableBundle> arg =
13452 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080013453 if (nai == null) break;
13454
Aaron Huang959d3642021-01-21 15:47:41 +080013455 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080013456 break;
13457 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080013458 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070013459 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080013460 break;
13461 }
13462 default: {
13463 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
13464 }
Cody Kesting73708bf2019-12-18 10:57:50 -080013465 }
13466 }
13467 }
13468
13469 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
13470 @VisibleForTesting
13471 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
13472 @NonNull private final IConnectivityDiagnosticsCallback mCb;
13473 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013474 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080013475
13476 @VisibleForTesting
13477 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013478 @NonNull IConnectivityDiagnosticsCallback cb,
13479 @NonNull NetworkRequestInfo nri,
13480 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080013481 mCb = cb;
13482 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013483 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080013484 }
13485
13486 @Override
13487 public void binderDied() {
13488 log("ConnectivityDiagnosticsCallback IBinder died.");
13489 unregisterConnectivityDiagnosticsCallback(mCb);
13490 }
13491 }
13492
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013493 /**
13494 * Class used for sending information from {@link
13495 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
13496 */
13497 private static class NetworkTestedResults {
13498 private final int mNetId;
13499 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013500 @Nullable private final String mRedirectUrl;
13501
13502 private NetworkTestedResults(
13503 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
13504 mNetId = netId;
13505 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013506 mRedirectUrl = redirectUrl;
13507 }
13508 }
13509
13510 /**
13511 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
13512 * ConnectivityDiagnosticsHandler}.
13513 */
13514 private static class ConnectivityReportEvent {
13515 private final long mTimestampMillis;
13516 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080013517 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013518
Aaron Huang959d3642021-01-21 15:47:41 +080013519 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
13520 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013521 mTimestampMillis = timestampMillis;
13522 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080013523 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013524 }
13525 }
13526
Cody Kestingf1120be2020-08-03 18:01:40 -070013527 /**
13528 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
13529 * ConnectivityDiagnosticsHandler}.
13530 */
13531 private static class ReportedNetworkConnectivityInfo {
13532 public final boolean hasConnectivity;
13533 public final boolean isNetworkRevalidating;
13534 public final int reporterUid;
13535 @NonNull public final NetworkAgentInfo nai;
13536
13537 private ReportedNetworkConnectivityInfo(
13538 boolean hasConnectivity,
13539 boolean isNetworkRevalidating,
13540 int reporterUid,
13541 @NonNull NetworkAgentInfo nai) {
13542 this.hasConnectivity = hasConnectivity;
13543 this.isNetworkRevalidating = isNetworkRevalidating;
13544 this.reporterUid = reporterUid;
13545 this.nai = nai;
13546 }
13547 }
13548
Cody Kesting73708bf2019-12-18 10:57:50 -080013549 private void handleRegisterConnectivityDiagnosticsCallback(
13550 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
13551 ensureRunningOnConnectivityServiceThread();
13552
13553 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080013554 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080013555 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
13556
James Mattis64b8b0f2020-11-24 17:40:49 -080013557 // Connectivity Diagnostics are meant to be used with a single network request. It would be
13558 // confusing for these networks to change when an NRI is satisfied in another layer.
13559 if (nri.isMultilayerRequest()) {
13560 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
13561 + "network requests.");
13562 }
13563
Cody Kesting73708bf2019-12-18 10:57:50 -080013564 // This means that the client registered the same callback multiple times. Do
13565 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080013566 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080013567 if (VDBG) log("Diagnostics callback is already registered");
13568
13569 // Decrement the reference count for this NetworkRequestInfo. The reference count is
13570 // incremented when the NetworkRequestInfo is created as part of
13571 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080013572 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080013573 return;
13574 }
13575
Cody Kesting31f1ff62020-03-05 10:46:02 -080013576 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080013577
13578 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080013579 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080013580 } catch (RemoteException e) {
13581 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080013582 return;
13583 }
13584
13585 // Once registered, provide ConnectivityReports for matching Networks
13586 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
13587 synchronized (mNetworkForNetId) {
13588 for (int i = 0; i < mNetworkForNetId.size(); i++) {
13589 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080013590 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
13591 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080013592 matchingNetworks.add(nai);
13593 }
13594 }
13595 }
13596 for (final NetworkAgentInfo nai : matchingNetworks) {
13597 final ConnectivityReport report = nai.getConnectivityReport();
13598 if (report == null) {
13599 continue;
13600 }
Junyu Lai71b51532024-02-01 10:39:01 +080013601 if (!hasConnectivityDiagnosticsPermissions(
Cody Kestingb77bf702020-02-12 14:50:58 -080013602 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
13603 continue;
13604 }
13605
13606 try {
13607 cb.onConnectivityReportAvailable(report);
13608 } catch (RemoteException e) {
13609 // Exception while sending the ConnectivityReport. Move on to the next network.
13610 }
Cody Kesting73708bf2019-12-18 10:57:50 -080013611 }
13612 }
13613
13614 private void handleUnregisterConnectivityDiagnosticsCallback(
13615 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
13616 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080013617 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080013618
Cody Kesting2b1a61c2020-03-30 12:43:49 -070013619 final ConnectivityDiagnosticsCallbackInfo cbInfo =
13620 mConnectivityDiagnosticsCallbacks.remove(iCb);
13621 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080013622 if (VDBG) log("Removing diagnostics callback that is not currently registered");
13623 return;
13624 }
13625
Cody Kesting2b1a61c2020-03-30 12:43:49 -070013626 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080013627
Cody Kesting70fa2b22020-12-02 12:16:56 -080013628 // Caller's UID must either be the registrants (if they are unregistering) or the System's
13629 // (if the Binder died)
13630 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
13631 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080013632 return;
13633 }
13634
Cody Kesting46cb1672020-03-04 13:35:20 -080013635 // Decrement the reference count for this NetworkRequestInfo. The reference count is
13636 // incremented when the NetworkRequestInfo is created as part of
13637 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080013638 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080013639
Cody Kesting31f1ff62020-03-05 10:46:02 -080013640 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080013641 }
13642
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013643 private void handleNetworkTestedWithExtras(
13644 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
13645 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080013646 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080013647 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013648 final ConnectivityReport report =
13649 new ConnectivityReport(
13650 reportEvent.mNai.network,
13651 reportEvent.mTimestampMillis,
13652 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080013653 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013654 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080013655 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070013656
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013657 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070013658 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013659 for (final IConnectivityDiagnosticsCallback cb : results) {
13660 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080013661 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013662 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070013663 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013664 }
13665 }
13666 }
13667
Cody Kestingb12ad4c2020-01-06 16:55:35 -080013668 private void handleDataStallSuspected(
13669 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
13670 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080013671 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080013672 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080013673 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080013674 new DataStallReport(
13675 nai.network,
13676 timestampMillis,
13677 detectionMethod,
13678 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080013679 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080013680 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080013681 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070013682 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080013683 for (final IConnectivityDiagnosticsCallback cb : results) {
13684 try {
13685 cb.onDataStallSuspected(report);
13686 } catch (RemoteException ex) {
13687 loge("Error invoking onDataStallSuspected", ex);
13688 }
13689 }
13690 }
13691
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080013692 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070013693 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
13694 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
13695 final ConnectivityReport cachedReport = nai.getConnectivityReport();
13696
13697 // If the Network is being re-validated as a result of this call to
13698 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
13699 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080013700 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070013701 getMatchingPermissionedCallbacks(
13702 nai,
13703 reportedNetworkConnectivityInfo.isNetworkRevalidating
13704 ? Process.INVALID_UID
13705 : reportedNetworkConnectivityInfo.reporterUid);
13706
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080013707 for (final IConnectivityDiagnosticsCallback cb : results) {
13708 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070013709 cb.onNetworkConnectivityReported(
13710 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080013711 } catch (RemoteException ex) {
13712 loge("Error invoking onNetworkConnectivityReported", ex);
13713 }
Cody Kestingf1120be2020-08-03 18:01:40 -070013714
13715 // If the Network isn't re-validating, also provide the cached report. If there is no
13716 // cached report, the Network is still being validated and a report will be sent once
13717 // validation is complete. Note that networks which never undergo validation will still
13718 // have a cached ConnectivityReport with RESULT_SKIPPED.
13719 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
13720 try {
13721 cb.onConnectivityReportAvailable(cachedReport);
13722 } catch (RemoteException ex) {
13723 loge("Error invoking onConnectivityReportAvailable", ex);
13724 }
13725 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080013726 }
13727 }
13728
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080013729 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090013730 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
13731 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080013732 sanitized.setUids(null);
13733 sanitized.setAdministratorUids(new int[0]);
13734 sanitized.setOwnerUid(Process.INVALID_UID);
13735 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080013736 }
13737
Cody Kestingf1120be2020-08-03 18:01:40 -070013738 /**
13739 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
13740 *
13741 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
13742 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013743 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070013744 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013745 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080013746 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013747 mConnectivityDiagnosticsCallbacks.entrySet()) {
13748 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
13749 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070013750
James Mattis64b8b0f2020-11-24 17:40:49 -080013751 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070013752 if (!nai.satisfies(nri.mRequests.get(0))) {
13753 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013754 }
Cody Kestingf1120be2020-08-03 18:01:40 -070013755
13756 // UID for this callback must either be:
13757 // - INVALID_UID (which sends callbacks to all UIDs), or
13758 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
13759 // notified as a result)
13760 if (uid != Process.INVALID_UID && uid != nri.mUid) {
13761 continue;
13762 }
13763
Junyu Lai71b51532024-02-01 10:39:01 +080013764 if (!hasConnectivityDiagnosticsPermissions(
Cody Kestingf1120be2020-08-03 18:01:40 -070013765 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
13766 continue;
13767 }
13768
13769 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013770 }
13771 return results;
13772 }
13773
Cody Kesting7474f672021-05-11 14:22:40 -070013774 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
13775 @NonNull NetworkAgentInfo nai) {
13776 // TODO(b/188483916): replace with a transport-agnostic location-aware check
13777 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
13778 }
13779
Cody Kesting160ef392021-05-05 13:17:22 -070013780 private boolean hasLocationPermission(String packageName, int uid) {
13781 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
13782 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
13783 // call in a try-catch.
13784 try {
13785 if (!mLocationPermissionChecker.checkLocationPermission(
13786 packageName, null /* featureId */, uid, null /* message */)) {
13787 return false;
13788 }
13789 } catch (SecurityException e) {
13790 return false;
13791 }
13792
13793 return true;
13794 }
13795
13796 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
Chalard Jean2f52a0e2025-03-21 10:14:28 +090013797 return anyNetworkAgentInfo(virtual ->
13798 virtual.propagateUnderlyingCapabilities()
13799 && virtual.networkCapabilities.getOwnerUid() == uid
13800 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network));
Cody Kesting160ef392021-05-05 13:17:22 -070013801 }
13802
Junyu Lai71b51532024-02-01 10:39:01 +080013803 @CheckResult
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013804 @VisibleForTesting
Junyu Lai71b51532024-02-01 10:39:01 +080013805 boolean hasConnectivityDiagnosticsPermissions(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013806 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
Junyu Lai71b51532024-02-01 10:39:01 +080013807 if (hasNetworkStackPermission(callbackPid, callbackUid)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013808 return true;
13809 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090013810 if (mAllowSysUiConnectivityReports
Junyu Lai71b51532024-02-01 10:39:01 +080013811 && hasSystemBarServicePermission(callbackPid, callbackUid)) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +090013812 return true;
13813 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013814
Cody Kesting160ef392021-05-05 13:17:22 -070013815 // Administrator UIDs also contains the Owner UID
13816 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
13817 if (!CollectionUtils.contains(administratorUids, callbackUid)
13818 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013819 return false;
13820 }
13821
Cody Kesting7474f672021-05-11 14:22:40 -070013822 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
13823 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013824 }
13825
Cody Kestingd199a9d2019-12-17 12:55:28 -080013826 @Override
13827 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013828 @NonNull IConnectivityDiagnosticsCallback callback,
13829 @NonNull NetworkRequest request,
13830 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070013831 Objects.requireNonNull(callback, "callback must not be null");
13832 Objects.requireNonNull(request, "request must not be null");
13833 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
13834
Cody Kesting73708bf2019-12-18 10:57:50 -080013835 if (request.legacyType != TYPE_NONE) {
13836 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
13837 + " Please use NetworkCapabilities instead.");
13838 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090013839 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080013840 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080013841
13842 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
13843 // and administrator uids to be safe.
13844 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Motomu Utsumiad480e02024-01-30 16:21:51 +090013845 restrictRequestNetworkCapabilitiesForCaller(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080013846
13847 final NetworkRequest requestWithId =
13848 new NetworkRequest(
13849 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
13850
13851 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
13852 //
13853 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
13854 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
13855 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013856 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Motomu Utsumib16f75c2024-05-23 19:25:17 +090013857 nri.mPerUidCounter.incrementCountOrThrow(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080013858 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080013859 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080013860
13861 mConnectivityDiagnosticsHandler.sendMessage(
13862 mConnectivityDiagnosticsHandler.obtainMessage(
13863 ConnectivityDiagnosticsHandler
13864 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
13865 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080013866 }
13867
13868 @Override
13869 public void unregisterConnectivityDiagnosticsCallback(
13870 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080013871 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080013872 mConnectivityDiagnosticsHandler.sendMessage(
13873 mConnectivityDiagnosticsHandler.obtainMessage(
13874 ConnectivityDiagnosticsHandler
13875 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090013876 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080013877 0,
13878 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080013879 }
Cody Kestingf53a0752020-04-15 12:33:28 -070013880
Yan Yanfe96dde2022-12-05 23:00:01 +000013881 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
13882 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
13883 if (underlyingNetworks == null) return false;
13884
13885 for (Network network : underlyingNetworks) {
13886 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
13887 return true;
13888 }
13889 }
13890 return false;
13891 }
13892
Cody Kestingf53a0752020-04-15 12:33:28 -070013893 @Override
13894 public void simulateDataStall(int detectionMethod, long timestampMillis,
13895 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070013896 Objects.requireNonNull(network, "network must not be null");
13897 Objects.requireNonNull(extras, "extras must not be null");
13898
paulhu3ffffe72021-09-16 10:15:22 +080013899 enforceAnyPermissionOf(mContext,
13900 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070013901 android.Manifest.permission.NETWORK_STACK);
13902 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000013903 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
13904 throw new SecurityException(
13905 "Data Stall simulation is only possible for test networks or networks built on"
13906 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070013907 }
13908
13909 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000013910 if (nai == null
13911 || (nai.creatorUid != mDeps.getCallingUid()
13912 && nai.creatorUid != Process.SYSTEM_UID)) {
13913 throw new SecurityException(
13914 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070013915 }
13916
Cody Kesting652e3ec2020-05-21 12:08:21 -070013917 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
13918 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
13919 // Data Stall information as a DataStallReportParcelable and passing to
13920 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
13921 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070013922 final DataStallReportParcelable p = new DataStallReportParcelable();
13923 p.timestampMillis = timestampMillis;
13924 p.detectionMethod = detectionMethod;
13925
13926 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
13927 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
13928 }
13929 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
13930 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
13931 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
13932 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
13933 }
13934
Serik Beketayevec8ad212020-12-07 22:43:07 -080013935 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070013936 }
lucaslin1a8b4c62021-01-21 02:02:55 +080013937
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090013938 /**
13939 * Class to hold the information for network activity change event from idle timers
13940 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
13941 */
13942 private static final class NetworkActivityParams {
13943 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090013944 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
13945 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090013946 public final int label;
13947 public final long timestampNs;
13948 // Uid represents the uid that was responsible for waking the radio.
13949 // -1 for no uid and uid is -1 if isActive is false.
13950 public final int uid;
13951
13952 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
13953 this.isActive = isActive;
13954 this.label = label;
13955 this.timestampNs = timestampNs;
13956 this.uid = uid;
13957 }
13958 }
13959
lucaslin66f44212021-02-23 01:12:55 +080013960 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
13961 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090013962 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080013963 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090013964 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
13965 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080013966 }
lucaslin37a16d92021-01-21 19:48:09 +080013967
13968 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090013969 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090013970 mHandler.post(() -> {
Chalard Jean2f52a0e2025-03-21 10:14:28 +090013971 forEachNetworkAgentInfo(nai ->
13972 nai.clatd.handleInterfaceLinkStateChanged(iface, up));
Chalard Jean5d05c4b2023-08-24 15:43:33 +090013973 });
lucaslin37a16d92021-01-21 19:48:09 +080013974 }
13975
13976 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090013977 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090013978 mHandler.post(() -> {
Chalard Jean2f52a0e2025-03-21 10:14:28 +090013979 forEachNetworkAgentInfo(nai ->
13980 nai.clatd.handleInterfaceRemoved(iface));
Chalard Jean5d05c4b2023-08-24 15:43:33 +090013981 });
lucaslin66f44212021-02-23 01:12:55 +080013982 }
13983 }
13984
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090013985 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080013986 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
13987
13988 /**
13989 * Class used for updating network activity tracking with netd and notify network activity
13990 * changes.
13991 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090013992 @VisibleForTesting
13993 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080013994 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080013995 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080013996 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090013997 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080013998 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
13999 new RemoteCallbackList<>();
14000 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090014001 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090014002 // If there is no default network, default network is considered active to keep the existing
14003 // behavior. Initial value is used until first connect to the default network.
14004 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014005 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090014006 // Key is netId. Value is configured idle timer information.
14007 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014008 private final boolean mTrackMultiNetworkActivities;
Suprabh Shuklac623c942024-10-15 17:19:07 -070014009 private final int mDefaultCellularDataInactivityTimeout;
14010 private final int mDefaultWifiDataInactivityTimeout;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014011 // Store netIds of Wi-Fi networks whose idletimers report that they are active
14012 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
14013 // Store netIds of cellular networks whose idletimers report that they are active
14014 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080014015
Chalard Jean46bfbf02022-02-02 00:56:25 +090014016 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080014017 public final int timeout;
14018 public final int transportType;
14019
14020 IdleTimerParams(int timeout, int transport) {
14021 this.timeout = timeout;
14022 this.transportType = transport;
14023 }
14024 }
14025
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090014026 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Suprabh Shuklac623c942024-10-15 17:19:07 -070014027 @NonNull Handler handler, boolean trackMultiNetworkActivities,
14028 int defaultCellularDataInactivityTimeout, int defaultWifiDataInactivityTimeout) {
lucaslin1a8b4c62021-01-21 02:02:55 +080014029 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080014030 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090014031 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014032 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Suprabh Shuklac623c942024-10-15 17:19:07 -070014033 mDefaultCellularDataInactivityTimeout = defaultCellularDataInactivityTimeout;
14034 mDefaultWifiDataInactivityTimeout = defaultWifiDataInactivityTimeout;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090014035 }
14036
14037 private void ensureRunningOnConnectivityServiceThread() {
Paul Huc0e70972024-10-04 06:22:24 +000014038 HandlerUtils.ensureRunningOnHandlerThread(mHandler);
lucaslin1a8b4c62021-01-21 02:02:55 +080014039 }
14040
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014041 /**
14042 * Update network activity and call BatteryStats to update radio power state if the
14043 * mobile or Wi-Fi activity is changed.
14044 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
14045 * mobile network is active since BatteryStatsService only maintains a single power state
14046 * for the mobile network.
14047 * The Wi-Fi network is also the same.
14048 *
14049 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
14050 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
14051 * transports.
14052 */
14053 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
14054 final boolean isActive, final int uid) {
14055 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
14056 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
14057 + transportType);
14058 return;
14059 }
14060 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
14061 ? mActiveWifiNetworks : mActiveCellularNetworks;
14062
14063 final boolean wasEmpty = activeNetworks.isEmpty();
14064 if (isActive) {
14065 activeNetworks.add(netId);
14066 } else {
14067 activeNetworks.remove(netId);
14068 }
14069
14070 if (wasEmpty != activeNetworks.isEmpty()) {
14071 updateRadioPowerState(isActive, transportType, uid);
14072 }
14073 }
14074
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014075 private void handleDefaultNetworkActivity(final int transportType,
14076 final boolean isActive, final long timestampNs) {
14077 mIsDefaultNetworkActive = isActive;
14078 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
14079 isActive, timestampNs);
14080 if (isActive) {
14081 reportNetworkActive();
14082 }
14083 }
14084
14085 private void handleReportNetworkActivityWithNetIdLabel(
14086 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014087 final int netId = activityParams.label;
14088 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014089 if (idleTimerParams == null) {
14090 // This network activity change is not tracked anymore
14091 // This can happen if netd callback post activity change event message but idle
14092 // timer is removed before processing this message.
14093 return;
14094 }
14095 // TODO: if a network changes transports, storing the transport type in the
14096 // IdleTimerParams is not correct. Consider getting it from the network's
14097 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014098 final int transportType = idleTimerParams.transportType;
14099 maybeUpdateRadioPowerState(netId, transportType,
14100 activityParams.isActive, activityParams.uid);
14101
14102 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
14103 // This activity change is not for the default network.
14104 return;
14105 }
14106
14107 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014108 activityParams.timestampNs);
14109 }
14110
14111 private void handleReportNetworkActivityWithTransportTypeLabel(
14112 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090014113 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090014114 // This activity change is not for the current default network.
14115 // This can happen if netd callback post activity change event message but
14116 // the default network is lost before processing this message.
14117 return;
14118 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014119 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
14120 activityParams.timestampNs);
14121 }
14122
14123 /**
14124 * Handle network activity change
14125 */
14126 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
14127 ensureRunningOnConnectivityServiceThread();
14128 if (mTrackMultiNetworkActivities) {
14129 handleReportNetworkActivityWithNetIdLabel(activityParams);
14130 } else {
14131 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080014132 }
14133 }
lucaslin1a8b4c62021-01-21 02:02:55 +080014134
lucaslin1193a5d2021-01-21 02:04:15 +080014135 private void reportNetworkActive() {
14136 final int length = mNetworkActivityListeners.beginBroadcast();
14137 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
14138 try {
14139 for (int i = 0; i < length; i++) {
14140 try {
14141 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
14142 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090014143 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080014144 }
14145 }
14146 } finally {
14147 mNetworkActivityListeners.finishBroadcast();
14148 }
14149 }
14150
lucaslin1a8b4c62021-01-21 02:02:55 +080014151 // This is deprecated and only to support legacy use cases.
14152 private int transportTypeToLegacyType(int type) {
14153 switch (type) {
14154 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090014155 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080014156 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090014157 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080014158 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090014159 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080014160 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090014161 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080014162 default:
14163 loge("Unexpected transport in transportTypeToLegacyType: " + type);
14164 }
14165 return ConnectivityManager.TYPE_NONE;
14166 }
14167
14168 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
14169 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
14170 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
14171 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
14172 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
14173 final long ident = Binder.clearCallingIdentity();
14174 try {
14175 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
14176 RECEIVE_DATA_ACTIVITY_CHANGE,
14177 null /* resultReceiver */,
14178 null /* scheduler */,
14179 0 /* initialCode */,
14180 null /* initialData */,
14181 null /* initialExtra */);
14182 } finally {
14183 Binder.restoreCallingIdentity(ident);
14184 }
14185 }
14186
14187 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014188 * Get idle timer label
14189 */
14190 @VisibleForTesting
14191 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
14192 final int netId, final int transportType) {
14193 return trackMultiNetworkActivities ? netId : transportType;
14194 }
14195
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014196 private boolean maybeCreateIdleTimer(
14197 String iface, int netId, int timeout, int transportType) {
14198 if (timeout <= 0 || iface == null) return false;
14199 try {
14200 final String label = Integer.toString(getIdleTimerLabel(
14201 mTrackMultiNetworkActivities, netId, transportType));
14202 mNetd.idletimerAddInterface(iface, timeout, label);
14203 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
14204 return true;
14205 } catch (Exception e) {
14206 loge("Exception in createIdleTimer", e);
14207 return false;
14208 }
14209 }
14210
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014211 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080014212 * Setup data activity tracking for the given network.
14213 *
14214 * Every {@code setupDataActivityTracking} should be paired with a
14215 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090014216 *
14217 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080014218 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090014219 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090014220 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080014221 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090014222 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080014223
14224 final int timeout;
14225 final int type;
14226
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090014227 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
14228 // Do not track VPN network.
14229 return false;
14230 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080014231 NetworkCapabilities.TRANSPORT_CELLULAR)) {
14232 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080014233 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
Suprabh Shuklac623c942024-10-15 17:19:07 -070014234 mDefaultCellularDataInactivityTimeout);
lucaslin1a8b4c62021-01-21 02:02:55 +080014235 type = NetworkCapabilities.TRANSPORT_CELLULAR;
14236 } else if (networkAgent.networkCapabilities.hasTransport(
14237 NetworkCapabilities.TRANSPORT_WIFI)) {
14238 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080014239 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
Suprabh Shuklac623c942024-10-15 17:19:07 -070014240 mDefaultWifiDataInactivityTimeout);
lucaslin1a8b4c62021-01-21 02:02:55 +080014241 type = NetworkCapabilities.TRANSPORT_WIFI;
14242 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090014243 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080014244 }
14245
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014246 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
14247 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
14248 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
14249 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
14250 // state only about a network that has an idletimer.
14251 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080014252 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014253 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080014254 }
14255
14256 /**
14257 * Remove data activity tracking when network disconnects.
14258 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090014259 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
14260 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080014261 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090014262 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080014263 final NetworkCapabilities caps = networkAgent.networkCapabilities;
14264
lucaslinb961efc2021-01-21 02:03:17 +080014265 if (iface == null) return;
14266
14267 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090014268 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
14269 // Do not track VPN network.
14270 return;
14271 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080014272 type = NetworkCapabilities.TRANSPORT_CELLULAR;
14273 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
14274 type = NetworkCapabilities.TRANSPORT_WIFI;
14275 } else {
14276 return; // do not track any other networks
14277 }
14278
14279 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014280 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090014281 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090014282 if (params == null) {
14283 // IdleTimer is not added if the configured timeout is 0 or negative value
14284 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080014285 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090014286 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014287 final String label = Integer.toString(getIdleTimerLabel(
14288 mTrackMultiNetworkActivities, netId, params.transportType));
14289 // The call fails silently if no idle timer setup for this interface
14290 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080014291 } catch (Exception e) {
14292 // You shall not crash!
14293 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080014294 }
14295 }
14296
Motomu Utsumi6225d572023-05-29 15:08:57 +090014297 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
14298 boolean hasIdleTimer) {
14299 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014300 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090014301 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090014302 // If only the default network is tracked, callbacks are called only when the
14303 // network has the idle timer.
14304 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090014305 reportNetworkActive();
14306 }
14307 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014308 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090014309 // If there is no default network, default network is considered active to keep the
14310 // existing behavior.
14311 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090014312 }
14313 }
14314
lucaslin1a8b4c62021-01-21 02:02:55 +080014315 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090014316 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080014317 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090014318 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080014319 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090014320 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090014321 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
14322 // first connected and remove when the network is disconnected.
14323 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
14324 // becomes the default network and remove when the network becomes no longer the default
14325 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090014326 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090014327 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090014328 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080014329 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090014330 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090014331 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080014332 removeDataActivityTracking(oldNetwork);
14333 }
14334 }
lucaslinb961efc2021-01-21 02:03:17 +080014335
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014336 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080014337 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
14338 switch (transportType) {
14339 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014340 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080014341 break;
14342 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014343 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080014344 break;
14345 default:
14346 logw("Untracked transport type:" + transportType);
14347 }
14348 }
lucaslin1193a5d2021-01-21 02:04:15 +080014349
14350 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090014351 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080014352 }
14353
14354 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
14355 mNetworkActivityListeners.register(l);
14356 }
14357
14358 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
14359 mNetworkActivityListeners.unregister(l);
14360 }
lucaslin012f7a12021-01-21 02:04:35 +080014361
14362 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014363 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Suprabh Shuklac623c942024-10-15 17:19:07 -070014364
14365 pw.print("mDefaultCellularDataInactivityTimeout=");
14366 pw.println(mDefaultCellularDataInactivityTimeout);
14367 pw.print("mDefaultWifiDataInactivityTimeout=");
14368 pw.println(mDefaultWifiDataInactivityTimeout);
14369
Motomu Utsumic298cf02023-05-31 12:06:12 +090014370 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090014371 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090014372 pw.println("Idle timers:");
14373 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090014374 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
14375 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
14376 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080014377 pw.print(" timeout="); pw.print(params.timeout);
14378 pw.print(" type="); pw.println(params.transportType);
14379 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014380 pw.println("WiFi active networks: " + mActiveWifiNetworks);
14381 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090014382 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090014383 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
14384 // be accessed from handler thread, except dump(). As dump() is never called in
14385 // normal usage, it would be needlessly expensive to lock the collection only for
14386 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090014387 // So catching the exception and logging.
14388 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080014389 }
14390 }
lucaslin1a8b4c62021-01-21 02:02:55 +080014391 }
James Mattis47db0582021-01-01 14:13:35 -080014392
Daniel Brightf9e945b2020-06-15 16:10:01 -070014393 /**
14394 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
14395 *
14396 * @param socketInfo the socket information
14397 * @param callback the callback to register
14398 */
14399 @Override
14400 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
14401 @NonNull final IQosCallback callback) {
14402 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
14403 if (nai == null || nai.networkCapabilities == null) {
14404 try {
14405 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
14406 } catch (final RemoteException ex) {
14407 loge("registerQosCallbackInternal: RemoteException", ex);
14408 }
14409 return;
14410 }
14411 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
14412 }
14413
14414 /**
14415 * Register a {@link IQosCallback} with base {@link QosFilter}.
14416 *
14417 * @param filter the filter to register
14418 * @param callback the callback to register
14419 * @param nai the agent information related to the filter's network
14420 */
14421 @VisibleForTesting
14422 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
14423 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090014424 Objects.requireNonNull(filter, "filter must be non-null");
14425 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070014426
14427 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080014428 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
14429 // on this network is unregistered when the app loses permission or b) no QoS
14430 // callbacks are sent for restricted networks unless the app currently has permission
14431 // to access restricted networks.
14432 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070014433 }
14434 mQosCallbackTracker.registerCallback(callback, filter, nai);
14435 }
14436
14437 /**
14438 * Unregisters the given callback.
14439 *
14440 * @param callback the callback to unregister
14441 */
14442 @Override
14443 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080014444 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070014445 mQosCallbackTracker.unregisterCallback(callback);
14446 }
James Mattis47db0582021-01-01 14:13:35 -080014447
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070014448 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
14449 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
14450 // Enterprise device can be fully managed like device owner and such use case
14451 // also should be supported. Calling app check for work profile and fully managed device
14452 // is already done in DevicePolicyManager.
14453 // This check is an extra caution to be sure device is fully managed or not.
14454 final UserManager um = mContext.getSystemService(UserManager.class);
14455 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
14456 if (um.isManagedProfile(profile.getIdentifier())) {
14457 return true;
14458 }
Kholoud Mohamed7a7d1ac2024-04-19 09:35:36 +000014459
14460 return mDeps.isAtLeastT() && dpm.getDeviceOwnerComponentOnAnyUser() != null;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070014461 }
14462
James Mattis45d81842021-01-10 14:24:24 -080014463 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070014464 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090014465 *
14466 * See the documentation for the individual preferences for a description of the supported
14467 * behaviors.
14468 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070014469 * @param profile If the device owner is set, any profile is allowed.
14470 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014471 * @param preferences the list of profile network preferences for the
14472 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090014473 * @param listener an optional listener to listen for completion of the operation.
14474 */
14475 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014476 public void setProfileNetworkPreferences(
14477 @NonNull final UserHandle profile,
14478 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090014479 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014480 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014481 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014482
14483 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070014484 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
14485 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
14486 .build();
14487 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014488 }
14489
paulhu3ffffe72021-09-16 10:15:22 +080014490 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014491 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014492 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014493 }
14494 if (profile.getIdentifier() < 0) {
14495 throw new IllegalArgumentException("Must explicitly specify a user handle ("
14496 + "UserHandle.CURRENT not supported)");
14497 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070014498 if (!isNetworkPreferenceAllowedForProfile(profile)) {
14499 throw new IllegalArgumentException("Profile must be a managed profile "
14500 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014501 }
paulhuaa0743d2021-05-26 21:56:03 +080014502
Chalard Jean0606fc82022-12-14 20:34:43 +090014503 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070014504 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014505 for (final ProfileNetworkPreference preference : preferences) {
14506 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070014507 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080014508 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014509 switch (preference.getPreference()) {
14510 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
14511 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070014512 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080014513 if (preference.getPreferenceEnterpriseId() != 0) {
14514 throw new IllegalArgumentException(
14515 "Invalid enterprise identifier in setProfileNetworkPreferences");
14516 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014517 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080014518 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
14519 blockingNonEnterprise = true;
14520 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080014521 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
14522 allowFallback = false;
14523 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014524 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070014525 // This code is needed even though there is a check later on,
14526 // because isRangeAlreadyInPreferenceList assumes that every preference
14527 // has a UID list.
14528 if (hasDefaultPreference) {
14529 throw new IllegalArgumentException(
14530 "Default profile preference should not be set along with other "
14531 + "preference");
14532 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080014533 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
14534 throw new IllegalArgumentException(
14535 "Invalid enterprise identifier in setProfileNetworkPreferences");
14536 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080014537 final Set<UidRange> uidRangeSet =
14538 getUidListToBeAppliedForNetworkPreference(profile, preference);
14539 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
14540 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
14541 } else {
14542 throw new IllegalArgumentException(
14543 "Overlapping uid range in setProfileNetworkPreferences");
14544 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014545 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080014546 nc.addEnterpriseId(
14547 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014548 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
14549 break;
14550 default:
14551 throw new IllegalArgumentException(
14552 "Invalid preference in setProfileNetworkPreferences");
14553 }
Junyu Lai35665cc2022-12-19 17:37:48 +080014554 preferenceList.add(new ProfileNetworkPreferenceInfo(
14555 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070014556 if (hasDefaultPreference && preferenceList.size() > 1) {
14557 throw new IllegalArgumentException(
14558 "Default profile preference should not be set along with other preference");
14559 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014560 }
14561 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014562 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014563 }
14564
Sooraj Sasindran499117f2021-11-29 12:40:09 -080014565 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
14566 @NonNull final UserHandle profile,
14567 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
14568 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080014569 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
14570 profileNetworkPreference.getIncludedUids());
14571
Sooraj Sasindran499117f2021-11-29 12:40:09 -080014572 if (uidRangeSet.size() > 0) {
14573 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
14574 throw new IllegalArgumentException(
14575 "Allow uid range is outside the uid range of profile.");
14576 }
14577 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080014578 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080014579 profileNetworkPreference.getExcludedUids());
14580 if (disallowUidRangeSet.size() > 0) {
14581 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
14582 throw new IllegalArgumentException(
14583 "disallow uid range is outside the uid range of profile.");
14584 }
14585 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
14586 disallowUidRangeSet);
14587 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090014588 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080014589 uidRangeSet.add(profileUids);
14590 }
14591 }
14592 return uidRangeSet;
14593 }
14594
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080014595 private boolean isEnterpriseIdentifierValid(
14596 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090014597 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080014598 return true;
14599 }
14600 return false;
14601 }
14602
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014603 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090014604 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014605 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090014606 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080014607 // The NRI for a user should contain the request for capabilities.
14608 // If fallback to default network is needed then NRI should include
14609 // the request for the default network. Create an image of it to
14610 // have the correct UIDs in it (also a request can only be part of one NRI, because
14611 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014612 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
14613 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080014614 if (pref.allowFallback) {
14615 nrs.add(createDefaultInternetRequestForTransport(
14616 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
14617 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080014618 if (VDBG) {
14619 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
14620 pref.capabilities.getUids()));
14621 }
14622
Chiachang Wang8156c4e2021-03-19 00:45:39 +000014623 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080014624 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080014625 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014626 result.add(nri);
14627 }
14628 return result;
14629 }
14630
Sooraj Sasindran499117f2021-11-29 12:40:09 -080014631 /**
14632 * Compare if the given UID range sets have the same UIDs.
14633 *
14634 */
14635 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090014636 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080014637 @NonNull Set<UidRange> uidRangeSet) {
14638 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
14639 return false;
14640 }
Chalard Jean0606fc82022-12-14 20:34:43 +090014641 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080014642 if (UidRangeUtils.doesRangeSetOverlap(
14643 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
14644 return true;
14645 }
14646 }
14647 return false;
14648 }
14649
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014650 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090014651 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014652 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070014653 /*
14654 * handleSetProfileNetworkPreference is always called for single user.
14655 * preferenceList only contains preferences for different uids within the same user
14656 * (enforced by getUidListToBeAppliedForNetworkPreference).
14657 * Clear all the existing preferences for the user before applying new preferences.
14658 *
14659 */
Chalard Jean0606fc82022-12-14 20:34:43 +090014660 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
14661 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080014662 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
14663 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070014664
paulhu74128522021-09-28 02:29:03 +000014665 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
14666 addPerAppDefaultNetworkRequests(
14667 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080014668 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080014669
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014670 // Finally, rematch.
14671 rematchAllNetworksAndRequests();
14672
14673 if (null != listener) {
14674 try {
14675 listener.onComplete();
14676 } catch (RemoteException e) {
14677 loge("Listener for setProfileNetworkPreference has died");
14678 }
14679 }
14680 }
14681
paulhu51f77dc2021-06-07 02:34:20 +000014682 @VisibleForTesting
14683 @NonNull
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000014684 ArraySet<NetworkRequestInfo> createNrisForPreferenceOrder(@NonNull final Set<Integer> uids,
14685 @NonNull final List<NetworkRequest> requests,
14686 final int preferenceOrder) {
paulhu51f77dc2021-06-07 02:34:20 +000014687 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
14688 if (uids.size() == 0) {
14689 // Should not create NetworkRequestInfo if no preferences. Without uid range in
14690 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
paulhu51f77dc2021-06-07 02:34:20 +000014691 return nris;
14692 }
14693
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000014694 final Set<UidRange> ranges = new ArraySet<>();
14695 for (final int uid : uids) {
14696 ranges.add(new UidRange(uid, uid));
14697 }
14698 setNetworkRequestUids(requests, ranges);
14699 nris.add(new NetworkRequestInfo(Process.myUid(), requests, preferenceOrder));
14700 return nris;
14701 }
14702
14703 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
14704 @NonNull final Set<Integer> uids) {
paulhu51f77dc2021-06-07 02:34:20 +000014705 final List<NetworkRequest> requests = new ArrayList<>();
14706 // The NRI should be comprised of two layers:
14707 // - The request for the mobile network preferred.
14708 // - The request for the default network, for fallback.
14709 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090014710 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000014711 requests.add(createDefaultInternetRequestForTransport(
14712 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000014713 return createNrisForPreferenceOrder(uids, requests, PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED
14714 );
14715 }
14716
14717 ArraySet<NetworkRequestInfo> createMultiLayerNrisFromSatelliteNetworkFallbackUids(
14718 @NonNull final Set<Integer> uids) {
14719 final List<NetworkRequest> requests = new ArrayList<>();
14720
14721 // request: track default(unrestricted internet network)
14722 requests.add(createDefaultInternetRequestForTransport(
14723 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
14724
Motomu Utsumiab750ab2024-05-31 18:15:07 +090014725 // request: Satellite internet, satellite network could be restricted or constrained
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000014726 final NetworkCapabilities cap = new NetworkCapabilities.Builder()
14727 .addCapability(NET_CAPABILITY_INTERNET)
14728 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
14729 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED)
Motomu Utsumiab750ab2024-05-31 18:15:07 +090014730 .removeCapability(NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED)
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000014731 .addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE)
14732 .build();
14733 requests.add(createNetworkRequest(NetworkRequest.Type.REQUEST, cap));
14734
14735 return createNrisForPreferenceOrder(uids, requests, PREFERENCE_ORDER_SATELLITE_FALLBACK);
paulhu51f77dc2021-06-07 02:34:20 +000014736 }
14737
14738 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000014739 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000014740 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
14741 addPerAppDefaultNetworkRequests(
14742 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000014743 // Finally, rematch.
14744 rematchAllNetworksAndRequests();
14745 }
14746
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000014747 private void handleSetSatelliteNetworkPreference(
14748 @NonNull final Set<Integer> satelliteNetworkPreferredUids) {
14749 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_SATELLITE_FALLBACK);
14750 addPerAppDefaultNetworkRequests(
14751 createMultiLayerNrisFromSatelliteNetworkFallbackUids(satelliteNetworkPreferredUids)
14752 );
14753 // Finally, rematch.
14754 rematchAllNetworksAndRequests();
14755 }
14756
Patrick Rohr2857ac42022-01-21 14:58:16 +010014757 private void handleIngressRateLimitChanged() {
14758 final long oldIngressRateLimit = mIngressRateLimit;
14759 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
14760 mContext);
Chalard Jean2f52a0e2025-03-21 10:14:28 +090014761 forEachNetworkAgentInfo(networkAgent -> {
Patrick Rohr2857ac42022-01-21 14:58:16 +010014762 if (canNetworkBeRateLimited(networkAgent)) {
14763 // If rate limit has previously been enabled, remove the old limit first.
14764 if (oldIngressRateLimit >= 0) {
14765 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
14766 }
14767 if (mIngressRateLimit >= 0) {
14768 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
14769 mIngressRateLimit);
14770 }
14771 }
Chalard Jean2f52a0e2025-03-21 10:14:28 +090014772 });
Patrick Rohr2857ac42022-01-21 14:58:16 +010014773 }
14774
14775 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090014776 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090014777 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090014778
Patrick Rohrff3b3f82022-02-09 15:15:52 +010014779 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
14780 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
14781 // internet connectivity can be rate limited.
14782 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
14783 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010014784 return false;
14785 }
14786
14787 final String iface = networkAgent.linkProperties.getInterfaceName();
14788 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010014789 // This may happen in tests, but if there is no interface then there is nothing that
14790 // can be rate limited.
14791 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010014792 return false;
14793 }
14794 return true;
14795 }
14796
James Mattis45d81842021-01-10 14:24:24 -080014797 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080014798 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
14799 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080014800 }
14801
14802 /**
14803 * Used by automotive devices to set the network preferences used to direct traffic at an
14804 * application level as per the given OemNetworkPreferences. An example use-case would be an
14805 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
14806 * vehicle via a particular network.
14807 *
14808 * Calling this will overwrite the existing preference.
14809 *
James Mattisda32cfe2021-01-26 16:23:52 -080014810 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090014811 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080014812 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080014813 */
James Mattis47db0582021-01-01 14:13:35 -080014814 @Override
James Mattis45d81842021-01-10 14:24:24 -080014815 public void setOemNetworkPreference(
14816 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090014817 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080014818
James Mattisfa270db2021-05-31 17:11:10 -070014819 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
14820 // Only bypass the permission/device checks if this is a valid test request.
14821 if (isValidTestOemNetworkPreference(preference)) {
14822 enforceManageTestNetworksPermission();
14823 } else {
14824 enforceAutomotiveDevice();
14825 enforceOemNetworkPreferencesPermission();
14826 validateOemNetworkPreferences(preference);
14827 }
James Mattis45d81842021-01-10 14:24:24 -080014828
James Mattis45d81842021-01-10 14:24:24 -080014829 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
14830 new Pair<>(preference, listener)));
14831 }
14832
James Mattisfa270db2021-05-31 17:11:10 -070014833 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000014834 * Sets the specified UIDs to get/receive the VPN as the only default network.
14835 *
14836 * Calling this will overwrite the existing network preference for this session, and the
14837 * specified UIDs won't get any default network when no VPN is connected.
14838 *
14839 * @param session The VPN session which manages the passed UIDs.
14840 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
14841 * setting for this session if the array is empty. Null is not allowed, the
14842 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
14843 * @hide
14844 */
14845 @Override
14846 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
14847 Objects.requireNonNull(ranges);
14848 enforceNetworkStackOrSettingsPermission();
14849 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
14850 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
14851 throw new IllegalArgumentException(
14852 "setVpnNetworkPreference: Passed UID ranges overlap");
14853 }
14854
14855 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
14856 new VpnNetworkPreferenceInfo(session,
14857 new ArraySet<UidRange>(Arrays.asList(ranges)))));
14858 }
14859
14860 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
14861 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
14862
14863 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
14864 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
14865
14866 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
14867 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
14868 // Finally, rematch.
14869 rematchAllNetworksAndRequests();
14870 }
14871
14872 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
14873 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
14874 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
14875 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
14876 final List<NetworkRequest> requests = new ArrayList<>();
14877 // Request VPN only, so other networks won't be the fallback options when VPN is not
14878 // connected temporarily.
14879 requests.add(createVpnRequest());
14880 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
14881 setNetworkRequestUids(requests, uidRanges);
14882 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
14883 }
14884 return nris;
14885 }
14886
14887 /**
James Mattisfa270db2021-05-31 17:11:10 -070014888 * Check the validity of an OEM network preference to be used for testing purposes.
14889 * @param preference the preference to validate
14890 * @return true if this is a valid OEM network preference test request.
14891 */
14892 private boolean isValidTestOemNetworkPreference(
14893 @NonNull final OemNetworkPreferences preference) {
14894 // Allow for clearing of an existing OemNetworkPreference used for testing.
14895 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
14896 // changes after this check is complete. This is an unlikely scenario as calling of this API
14897 // is controlled by the OEM therefore the added complexity is not worth adding given those
14898 // circumstances. That said, it is an edge case to be aware of hence this comment.
14899 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
14900 && isTestOemNetworkPreference(mOemNetworkPreferences);
14901 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
14902 }
14903
14904 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
14905 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
14906 return prefMap.size() == 1
14907 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
14908 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
14909 }
14910
James Mattis45d81842021-01-10 14:24:24 -080014911 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
14912 for (@OemNetworkPreferences.OemNetworkPreference final int pref
14913 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070014914 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
14915 throw new IllegalArgumentException(
14916 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
14917 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080014918 }
14919 }
14920 }
14921
14922 private void handleSetOemNetworkPreference(
14923 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090014924 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080014925 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
14926 if (DBG) {
14927 log("set OEM network preferences :" + preference.toString());
14928 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090014929
James Mattiscb1e0362021-04-06 17:07:42 -070014930 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000014931 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
14932 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
14933 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080014934 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080014935
14936 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090014937 try {
14938 listener.onComplete();
14939 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080014940 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090014941 }
James Mattis45d81842021-01-10 14:24:24 -080014942 }
14943 }
14944
paulhu74128522021-09-28 02:29:03 +000014945 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080014946 // Skip the requests which are set by other network preference. Because the uid range rules
14947 // should stay in netd.
14948 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080014949 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080014950 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080014951 }
14952
James Mattis3ce3d3c2021-02-09 18:18:28 -080014953 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
14954 ensureRunningOnConnectivityServiceThread();
14955 mDefaultNetworkRequests.addAll(nris);
14956 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
14957 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080014958 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
Motomu Utsumid20727f2024-05-23 21:44:40 +090014959 // This method does not need to modify perUidCounter and mBlockedStatusTrackingUids because:
Motomu Utsumib16f75c2024-05-23 19:25:17 +090014960 // - |nris| only contains per-app network requests created by ConnectivityService which
Motomu Utsumid20727f2024-05-23 21:44:40 +090014961 // are internal requests and have no messenger and are not associated with any callbacks,
14962 // and so do not need to be tracked in perUidCounter and mBlockedStatusTrackingUids.
Motomu Utsumib16f75c2024-05-23 19:25:17 +090014963 // - The requests in perAppCallbackRequestsToUpdate are removed, modified, and re-added,
14964 // but the same number of requests is removed and re-added, and none of the requests
Motomu Utsumid20727f2024-05-23 21:44:40 +090014965 // changes mUid and mAsUid, so the perUidCounter and mBlockedStatusTrackingUids before
14966 // and after this method remains the same. Re-adding the requests does not modify
14967 // perUidCounter and mBlockedStatusTrackingUids (that is done when the app registers the
14968 // request), so removing them must not modify perUidCounter and mBlockedStatusTrackingUids
14969 // either.
Motomu Utsumib16f75c2024-05-23 19:25:17 +090014970 // TODO(b/341228979): Modify nris in place instead of removing them and re-adding them
14971 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate,
14972 false /* untrackUids */);
paulhu74128522021-09-28 02:29:03 +000014973 nrisToRegister.addAll(
14974 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
14975 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080014976 }
14977
14978 /**
14979 * All current requests that are tracking the default network need to be assessed as to whether
14980 * or not the current set of per-application default requests will be changing their default
14981 * network. If so, those requests will need to be updated so that they will send callbacks for
14982 * default network changes at the appropriate time. Additionally, those requests tracking the
14983 * default that were previously updated by this flow will need to be reassessed.
14984 * @return the nris which will need to be updated.
14985 */
14986 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
14987 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
14988 // Get the distinct nris to check since for multilayer requests, it is possible to have the
14989 // same nri in the map's values for each of its NetworkRequest objects.
14990 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080014991 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080014992 // Include this nri if it is currently being tracked.
14993 if (isPerAppTrackedNri(nri)) {
14994 defaultCallbackRequests.add(nri);
14995 continue;
14996 }
14997 // We only track callbacks for requests tracking the default.
14998 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
14999 continue;
15000 }
15001 // Include this nri if it will be tracked by the new per-app default requests.
15002 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090015003 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080015004 if (isNriGoingToBeTracked) {
15005 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080015006 }
15007 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080015008 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080015009 }
15010
James Mattis3ce3d3c2021-02-09 18:18:28 -080015011 /**
15012 * Create nris for those network requests that are currently tracking the default network that
15013 * are being controlled by a per-application default.
15014 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
15015 * foundation when creating the nri. Important items include the calling uid's original
15016 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
15017 * requests are assumed to have already been validated as needing to be updated.
15018 * @return the Set of nris to use when registering network requests.
15019 */
15020 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
15021 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
15022 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
15023 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
15024 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090015025 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080015026
Chalard Jean9473c982021-07-29 20:03:04 +090015027 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080015028 if (trackingNri == mDefaultRequest) {
15029 callbackRequestsToRegister.add(new NetworkRequestInfo(
15030 callbackRequest,
15031 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
15032 continue;
15033 }
15034
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090015035 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080015036 callbackRequestsToRegister.add(new NetworkRequestInfo(
15037 callbackRequest,
15038 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090015039 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090015040 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080015041 }
15042 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080015043 }
15044
Chalard Jean17215832021-03-01 14:06:28 +090015045 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
15046 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090015047 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000015048 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090015049 }
15050 }
15051
James Mattis45d81842021-01-10 14:24:24 -080015052 /**
15053 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
15054 */
15055 @VisibleForTesting
15056 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080015057 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080015058 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080015059 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080015060 final SparseArray<Set<Integer>> uids =
15061 createUidsFromOemNetworkPreferences(preference);
15062 for (int i = 0; i < uids.size(); i++) {
15063 final int key = uids.keyAt(i);
15064 final Set<Integer> value = uids.valueAt(i);
15065 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
15066 // No need to add an nri without any requests.
15067 if (0 == nri.mRequests.size()) {
15068 continue;
15069 }
15070 nris.add(nri);
15071 }
15072
15073 return nris;
15074 }
15075
15076 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
15077 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070015078 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080015079 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080015080 final List<UserHandle> users =
15081 mContext.getSystemService(UserManager.class).getUserHandles(true);
15082 if (null == users || users.size() == 0) {
15083 if (VDBG || DDBG) {
15084 log("No users currently available for setting the OEM network preference.");
15085 }
James Mattisb6b6a432021-06-01 22:30:36 -070015086 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080015087 }
James Mattis45d81842021-01-10 14:24:24 -080015088 for (final Map.Entry<String, Integer> entry :
15089 preference.getNetworkPreferences().entrySet()) {
15090 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070015091 // Add the rules for all users as this policy is device wide.
15092 for (final UserHandle user : users) {
15093 try {
15094 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
15095 if (!prefToUids.contains(pref)) {
15096 prefToUids.put(pref, new ArraySet<>());
15097 }
15098 prefToUids.get(pref).add(uid);
15099 } catch (PackageManager.NameNotFoundException e) {
15100 // Although this may seem like an error scenario, it is ok that uninstalled
15101 // packages are sent on a network preference as the system will watch for
15102 // package installations associated with this network preference and update
15103 // accordingly. This is done to minimize race conditions on app install.
15104 continue;
James Mattis45d81842021-01-10 14:24:24 -080015105 }
James Mattis45d81842021-01-10 14:24:24 -080015106 }
15107 }
James Mattisb6b6a432021-06-01 22:30:36 -070015108 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080015109 }
15110
15111 private NetworkRequestInfo createNriFromOemNetworkPreferences(
15112 @OemNetworkPreferences.OemNetworkPreference final int preference,
15113 @NonNull final Set<Integer> uids) {
15114 final List<NetworkRequest> requests = new ArrayList<>();
15115 // Requests will ultimately be evaluated by order of insertion therefore it matters.
15116 switch (preference) {
15117 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
15118 requests.add(createUnmeteredNetworkRequest());
15119 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070015120 requests.add(createDefaultInternetRequestForTransport(
15121 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080015122 break;
15123 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
15124 requests.add(createUnmeteredNetworkRequest());
15125 requests.add(createOemPaidNetworkRequest());
15126 break;
15127 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
15128 requests.add(createOemPaidNetworkRequest());
15129 break;
15130 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
15131 requests.add(createOemPrivateNetworkRequest());
15132 break;
James Mattisfa270db2021-05-31 17:11:10 -070015133 case OEM_NETWORK_PREFERENCE_TEST:
15134 requests.add(createUnmeteredNetworkRequest());
15135 requests.add(createTestNetworkRequest());
15136 requests.add(createDefaultRequest());
15137 break;
15138 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
15139 requests.add(createTestNetworkRequest());
15140 break;
James Mattis45d81842021-01-10 14:24:24 -080015141 default:
15142 // This should never happen.
15143 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
15144 + " called with invalid preference of " + preference);
15145 }
15146
James Mattisfa270db2021-05-31 17:11:10 -070015147 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090015148 for (final int uid : uids) {
15149 ranges.add(new UidRange(uid, uid));
15150 }
15151 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080015152 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080015153 }
15154
15155 private NetworkRequest createUnmeteredNetworkRequest() {
15156 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
15157 .addCapability(NET_CAPABILITY_NOT_METERED)
15158 .addCapability(NET_CAPABILITY_VALIDATED);
15159 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
15160 }
15161
15162 private NetworkRequest createOemPaidNetworkRequest() {
15163 // NET_CAPABILITY_OEM_PAID is a restricted capability.
15164 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
15165 .addCapability(NET_CAPABILITY_OEM_PAID)
15166 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
15167 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
15168 }
15169
15170 private NetworkRequest createOemPrivateNetworkRequest() {
15171 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
15172 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
15173 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
15174 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
15175 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
15176 }
15177
15178 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070015179 final NetworkCapabilities netcap = new NetworkCapabilities();
15180 netcap.addCapability(NET_CAPABILITY_INTERNET);
15181 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
15182 return netcap;
15183 }
15184
15185 private NetworkRequest createTestNetworkRequest() {
15186 final NetworkCapabilities netcap = new NetworkCapabilities();
15187 netcap.clearAll();
15188 netcap.addTransportType(TRANSPORT_TEST);
15189 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080015190 }
James Mattis47db0582021-01-01 14:13:35 -080015191 }
markchien738ad912021-12-09 18:15:45 +080015192
Junyu Lai38c75032023-12-04 07:52:19 +000015193 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080015194 @Override
Junyu Laidf210362023-10-24 02:47:50 +000015195 public void setDataSaverEnabled(final boolean enable) {
15196 enforceNetworkStackOrSettingsPermission();
15197 try {
15198 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
15199 if (!ret) {
15200 throw new IllegalStateException("Error when changing iptables: " + enable);
15201 }
15202 } catch (RemoteException e) {
15203 // Lack of permission or binder errors.
15204 throw new IllegalStateException(e);
15205 }
Ken Chen24330172023-10-20 13:02:14 +080015206
Motomu Utsumid20727f2024-05-23 21:44:40 +090015207 synchronized (mBlockedStatusTrackingUids) {
15208 try {
15209 mBpfNetMaps.setDataSaverEnabled(enable);
15210 } catch (ServiceSpecificException | UnsupportedOperationException e) {
15211 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
15212 return;
15213 }
15214
15215 if (shouldTrackUidsForBlockedStatusCallbacks()) {
15216 updateTrackingUidsBlockedReasons();
15217 }
Ken Chen24330172023-10-20 13:02:14 +080015218 }
Junyu Laidf210362023-10-24 02:47:50 +000015219 }
15220
Chalard Jeanc8fefb32023-09-05 21:41:13 +090015221 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
15222 throws PackageManager.NameNotFoundException {
15223 final PackageManager pm = mContext.getPackageManager();
15224 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
15225 if (appId < Process.FIRST_APPLICATION_UID) {
15226 throw new RuntimeException("Can't set package firewall rule for system app "
15227 + packageName + " with appId " + appId);
15228 }
15229 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
15230 final int uid = uh.getUid(appId);
15231 setUidFirewallRule(chain, uid, rule);
15232 }
15233 return appId;
15234 }
15235
markchiene1561fa2021-12-09 22:00:56 +080015236 @Override
markchien3c04e662022-03-22 16:29:56 +080015237 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080015238 enforceNetworkStackOrSettingsPermission();
15239
Suprabh Shukla724d8972024-03-26 16:59:11 -070015240 if (chain == FIREWALL_CHAIN_BACKGROUND && !mBackgroundFirewallChainEnabled) {
15241 Log.i(TAG, "Ignoring operation setUidFirewallRule on the background chain because the"
15242 + " feature is disabled.");
15243 return;
15244 }
15245
markchien3c04e662022-03-22 16:29:56 +080015246 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
15247 int firewallRule = getFirewallRuleType(chain, rule);
15248
15249 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
15250 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
15251 }
15252
Motomu Utsumid20727f2024-05-23 21:44:40 +090015253 synchronized (mBlockedStatusTrackingUids) {
15254 try {
15255 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
15256 } catch (ServiceSpecificException e) {
15257 throw new IllegalStateException(e);
15258 }
15259 if (shouldTrackUidsForBlockedStatusCallbacks()
15260 && mBlockedStatusTrackingUids.get(uid, 0) != 0) {
15261 mHandler.sendMessage(mHandler.obtainMessage(EVENT_BLOCKED_REASONS_CHANGED,
15262 List.of(new Pair<>(uid, mBpfNetMaps.getUidNetworkingBlockedReasons(uid)))));
15263 }
Motomu Utsumiff555a72024-05-23 23:22:40 +090015264 if (shouldTrackFirewallDestroySocketReasons()) {
15265 maybePostFirewallDestroySocketReasons(chain, Set.of(uid));
15266 }
markchiene1561fa2021-12-09 22:00:56 +080015267 }
15268 }
markchien98a6f952022-01-13 23:43:53 +080015269
Motomu Utsumia1a00342024-06-13 09:29:47 +000015270 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Chalard Jeanc8fefb32023-09-05 21:41:13 +090015271 private int getPackageFirewallRule(final int chain, final String packageName)
15272 throws PackageManager.NameNotFoundException {
15273 final PackageManager pm = mContext.getPackageManager();
15274 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
15275 return getUidFirewallRule(chain, appId);
15276 }
15277
Motomu Utsumia1a00342024-06-13 09:29:47 +000015278 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi900b8062023-01-19 16:16:49 +090015279 @Override
15280 public int getUidFirewallRule(final int chain, final int uid) {
15281 enforceNetworkStackOrSettingsPermission();
15282 return mBpfNetMaps.getUidRule(chain, uid);
15283 }
15284
markchien3c04e662022-03-22 16:29:56 +080015285 private int getFirewallRuleType(int chain, int rule) {
15286 final int defaultRule;
15287 switch (chain) {
15288 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000015289 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
15290 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000015291 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
Motomu Utsumi11d33452024-04-02 18:29:08 +090015292 case ConnectivityManager.FIREWALL_CHAIN_METERED_DENY_USER:
15293 case ConnectivityManager.FIREWALL_CHAIN_METERED_DENY_ADMIN:
markchien3c04e662022-03-22 16:29:56 +080015294 defaultRule = FIREWALL_RULE_ALLOW;
15295 break;
15296 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
15297 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
15298 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
15299 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080015300 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
Motomu Utsumi11d33452024-04-02 18:29:08 +090015301 case ConnectivityManager.FIREWALL_CHAIN_METERED_ALLOW:
markchien3c04e662022-03-22 16:29:56 +080015302 defaultRule = FIREWALL_RULE_DENY;
15303 break;
15304 default:
15305 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
15306 }
15307 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
15308
15309 return rule;
15310 }
15311
Motomu Utsumi2c248d22024-03-26 18:25:39 +090015312 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumiff555a72024-05-23 23:22:40 +090015313 private Set<Integer> getUidsOnFirewallChain(final int chain) throws ErrnoException {
15314 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
15315 return mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
15316 } else {
15317 return mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
15318 }
15319 }
15320
15321 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumid44a33a2023-03-28 18:08:12 +090015322 private void closeSocketsForFirewallChainLocked(final int chain)
15323 throws ErrnoException, SocketException, InterruptedIOException {
Motomu Utsumiff555a72024-05-23 23:22:40 +090015324 final Set<Integer> uidsOnChain = getUidsOnFirewallChain(chain);
Junyu Laie0031522023-08-29 18:32:57 +080015325 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090015326 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
15327 // So, close all non-system socket owned by uids that are not explicitly allowed
15328 Set<Range<Integer>> ranges = new ArraySet<>();
15329 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
Motomu Utsumiff555a72024-05-23 23:22:40 +090015330 mDeps.destroyLiveTcpSockets(ranges, uidsOnChain /* exemptUids */);
Motomu Utsumid44a33a2023-03-28 18:08:12 +090015331 } else {
15332 // Denylist means the firewall allows all by default, uids must be explicitly denied
15333 // So, close socket owned by uids that are explicitly denied
Motomu Utsumiff555a72024-05-23 23:22:40 +090015334 mDeps.destroyLiveTcpSocketsByOwnerUids(uidsOnChain /* ownerUids */);
Motomu Utsumid44a33a2023-03-28 18:08:12 +090015335 }
15336 }
15337
Motomu Utsumiff555a72024-05-23 23:22:40 +090015338 private void maybePostClearFirewallDestroySocketReasons(int chain) {
15339 if (chain != FIREWALL_CHAIN_BACKGROUND) {
15340 // TODO (b/300681644): Support other firewall chains
15341 return;
15342 }
15343 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CLEAR_FIREWALL_DESTROY_SOCKET_REASONS,
15344 DESTROY_SOCKET_REASON_FIREWALL_BACKGROUND, 0 /* arg2 */));
15345 }
15346
markchien98a6f952022-01-13 23:43:53 +080015347 @Override
15348 public void setFirewallChainEnabled(final int chain, final boolean enable) {
15349 enforceNetworkStackOrSettingsPermission();
15350
Suprabh Shukla724d8972024-03-26 16:59:11 -070015351 if (chain == FIREWALL_CHAIN_BACKGROUND && !mBackgroundFirewallChainEnabled) {
15352 Log.i(TAG, "Ignoring operation setFirewallChainEnabled on the background chain because"
15353 + " the feature is disabled.");
15354 return;
15355 }
Motomu Utsumi11d33452024-04-02 18:29:08 +090015356 if (METERED_ALLOW_CHAINS.contains(chain) || METERED_DENY_CHAINS.contains(chain)) {
15357 // Metered chains are used from a separate bpf program that is triggered by iptables
15358 // and can not be controlled by setFirewallChainEnabled.
15359 throw new UnsupportedOperationException(
15360 "Chain (" + chain + ") can not be controlled by setFirewallChainEnabled");
15361 }
Suprabh Shukla724d8972024-03-26 16:59:11 -070015362
Motomu Utsumid20727f2024-05-23 21:44:40 +090015363 synchronized (mBlockedStatusTrackingUids) {
15364 try {
15365 mBpfNetMaps.setChildChain(chain, enable);
15366 } catch (ServiceSpecificException e) {
15367 throw new IllegalStateException(e);
15368 }
15369 if (shouldTrackUidsForBlockedStatusCallbacks()) {
15370 updateTrackingUidsBlockedReasons();
15371 }
Motomu Utsumiff555a72024-05-23 23:22:40 +090015372 if (shouldTrackFirewallDestroySocketReasons() && !enable) {
15373 // Clear destroy socket reasons so that CS does not destroy sockets of apps that
15374 // have network access.
15375 maybePostClearFirewallDestroySocketReasons(chain);
15376 }
markchien98a6f952022-01-13 23:43:53 +080015377 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090015378
Chalard Jeandf29a852023-05-29 17:02:43 +090015379 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090015380 try {
15381 closeSocketsForFirewallChainLocked(chain);
15382 } catch (ErrnoException | SocketException | InterruptedIOException e) {
15383 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
15384 }
15385 }
markchien98a6f952022-01-13 23:43:53 +080015386 }
15387
Motomu Utsumid20727f2024-05-23 21:44:40 +090015388 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
15389 @GuardedBy("mBlockedStatusTrackingUids")
15390 private void updateTrackingUidsBlockedReasons() {
15391 if (mBlockedStatusTrackingUids.size() == 0) {
15392 return;
15393 }
15394 final ArrayList<Pair<Integer, Integer>> uidBlockedReasonsList = new ArrayList<>();
15395 for (int i = 0; i < mBlockedStatusTrackingUids.size(); i++) {
15396 final int uid = mBlockedStatusTrackingUids.keyAt(i);
15397 uidBlockedReasonsList.add(
15398 new Pair<>(uid, mBpfNetMaps.getUidNetworkingBlockedReasons(uid)));
15399 }
15400 mHandler.sendMessage(mHandler.obtainMessage(EVENT_BLOCKED_REASONS_CHANGED,
15401 uidBlockedReasonsList));
15402 }
15403
Motomu Utsumiff555a72024-05-23 23:22:40 +090015404 private int getFirewallDestroySocketReasons(final int blockedReasons) {
15405 int destroySocketReasons = DESTROY_SOCKET_REASON_NONE;
15406 if ((blockedReasons & BLOCKED_REASON_APP_BACKGROUND) != BLOCKED_REASON_NONE) {
15407 destroySocketReasons |= DESTROY_SOCKET_REASON_FIREWALL_BACKGROUND;
15408 }
15409 return destroySocketReasons;
15410 }
15411
15412 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
15413 @GuardedBy("mBlockedStatusTrackingUids")
15414 private void maybePostFirewallDestroySocketReasons(int chain, Set<Integer> uids) {
15415 if (chain != FIREWALL_CHAIN_BACKGROUND) {
15416 // TODO (b/300681644): Support other firewall chains
15417 return;
15418 }
15419 final ArrayList<Pair<Integer, Integer>> reasonsList = new ArrayList<>();
15420 for (int uid: uids) {
15421 final int blockedReasons = mBpfNetMaps.getUidNetworkingBlockedReasons(uid);
15422 final int destroySocketReaons = getFirewallDestroySocketReasons(blockedReasons);
15423 reasonsList.add(new Pair<>(uid, destroySocketReaons));
15424 }
15425 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UPDATE_FIREWALL_DESTROY_SOCKET_REASONS,
15426 reasonsList));
15427 }
15428
markchien00a0bed2022-01-13 23:46:13 +080015429 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000015430 public boolean getFirewallChainEnabled(final int chain) {
15431 enforceNetworkStackOrSettingsPermission();
15432
Motomu Utsumi11d33452024-04-02 18:29:08 +090015433 if (METERED_ALLOW_CHAINS.contains(chain) || METERED_DENY_CHAINS.contains(chain)) {
15434 // Metered chains are used from a separate bpf program that is triggered by iptables
15435 // and can not be controlled by setFirewallChainEnabled.
15436 throw new UnsupportedOperationException(
15437 "getFirewallChainEnabled can not return status of chain (" + chain + ")");
15438 }
15439
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000015440 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000015441 }
15442
15443 @Override
markchien00a0bed2022-01-13 23:46:13 +080015444 public void replaceFirewallChain(final int chain, final int[] uids) {
15445 enforceNetworkStackOrSettingsPermission();
15446
Suprabh Shukla724d8972024-03-26 16:59:11 -070015447 if (chain == FIREWALL_CHAIN_BACKGROUND && !mBackgroundFirewallChainEnabled) {
15448 Log.i(TAG, "Ignoring operation replaceFirewallChain on the background chain because"
15449 + " the feature is disabled.");
15450 return;
15451 }
15452
Motomu Utsumid20727f2024-05-23 21:44:40 +090015453 synchronized (mBlockedStatusTrackingUids) {
Motomu Utsumiff555a72024-05-23 23:22:40 +090015454 // replaceFirewallChain removes uids that are currently on the chain and put |uids| on
15455 // the chain.
15456 // So this method could change blocked reasons of uids that are currently on chain +
15457 // |uids|.
15458 final Set<Integer> affectedUids = new ArraySet<>();
15459 if (shouldTrackFirewallDestroySocketReasons()) {
15460 try {
15461 affectedUids.addAll(getUidsOnFirewallChain(chain));
15462 } catch (ErrnoException e) {
15463 Log.e(TAG, "Failed to get uids on chain(" + chain + "): " + e);
15464 }
15465 for (final int uid: uids) {
15466 affectedUids.add(uid);
15467 }
15468 }
Motomu Utsumid20727f2024-05-23 21:44:40 +090015469
Motomu Utsumiff555a72024-05-23 23:22:40 +090015470 mBpfNetMaps.replaceUidChain(chain, uids);
Motomu Utsumid20727f2024-05-23 21:44:40 +090015471 if (shouldTrackUidsForBlockedStatusCallbacks()) {
15472 updateTrackingUidsBlockedReasons();
15473 }
Motomu Utsumiff555a72024-05-23 23:22:40 +090015474 if (shouldTrackFirewallDestroySocketReasons()) {
15475 maybePostFirewallDestroySocketReasons(chain, affectedUids);
15476 }
Motomu Utsumid20727f2024-05-23 21:44:40 +090015477 }
markchien00a0bed2022-01-13 23:46:13 +080015478 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080015479
15480 @Override
15481 public IBinder getCompanionDeviceManagerProxyService() {
15482 enforceNetworkStackPermission(mContext);
15483 return mCdmps;
15484 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090015485
15486 @Override
15487 public IBinder getRoutingCoordinatorService() {
15488 enforceNetworkStackPermission(mContext);
15489 return mRoutingCoordinatorService;
15490 }
Remi NGUYEN VANaa355ac2024-05-29 17:56:17 +090015491
15492 @Override
15493 public long getEnabledConnectivityManagerFeatures() {
15494 long features = 0;
15495 // The bitmask must be built based on final properties initialized in the constructor, to
15496 // ensure that it does not change over time and is always consistent between
15497 // ConnectivityManager and ConnectivityService.
15498 if (mUseDeclaredMethodsForCallbacksEnabled) {
15499 features |= ConnectivityManager.FEATURE_USE_DECLARED_METHODS_FOR_CALLBACKS;
15500 }
Chalard Jean391ec5d2025-03-07 10:54:52 +090015501 if (mQueueNetworkAgentEventsInSystemServer) {
15502 features |= ConnectivityManager.FEATURE_QUEUE_NETWORK_AGENT_EVENTS_IN_SYSTEM_SERVER;
15503 }
Remi NGUYEN VANaa355ac2024-05-29 17:56:17 +090015504 return features;
15505 }
Motomu Utsumi9d5d7d02024-08-27 20:00:24 +090015506
15507 @Override
15508 public boolean isConnectivityServiceFeatureEnabledForTesting(String featureFlag) {
15509 switch (featureFlag) {
15510 case INGRESS_TO_VPN_ADDRESS_FILTERING:
15511 return mIngressToVpnAddressFiltering;
Chalard Jean391ec5d2025-03-07 10:54:52 +090015512 case QUEUE_NETWORK_AGENT_EVENTS_IN_SYSTEM_SERVER:
15513 return mQueueNetworkAgentEventsInSystemServer;
Motomu Utsumi9d5d7d02024-08-27 20:00:24 +090015514 default:
15515 throw new IllegalArgumentException("Unknown flag: " + featureFlag);
15516 }
15517 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070015518}