blob: 52f890d2b2f39a4568f07cd8c3fe0117d65fc364 [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;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090027import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
29import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
34import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Junyu Lai38c75032023-12-04 07:52:19 +000035import static android.net.ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090036import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
37import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000038import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-06-08 13:11:45 +080039import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070040import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080041import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
42import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
43import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090044import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090045import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090046import static android.net.ConnectivityManager.TYPE_MOBILE;
47import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
49import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
50import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
51import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
52import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
53import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
54import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
55import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070056import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090057import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070058import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090059import static android.net.ConnectivityManager.TYPE_WIFI;
60import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070061import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070062import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080063import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080067import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Yang Sunca537d52024-01-19 12:53:50 +080068import static android.net.MulticastRoutingConfig.FORWARD_NONE;
Paul Jensen53f08952015-06-16 14:27:36 -040069import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
76import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080079import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090080import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080081import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
82import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080083import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090084import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090085import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080086import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
87import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080088import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
89import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
90import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090091import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090092import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060093import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070094import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080095import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090096import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070097import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
98import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070099import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +0800100import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100101import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700102import static android.system.OsConstants.IPPROTO_TCP;
103import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900104
Junyu Lai155760b2023-10-05 14:51:00 +0800105import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
108import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
109import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900110import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
paulhu3ffffe72021-09-16 10:15:22 +0800111import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
112import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
113import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Junyu Lai71b51532024-02-01 10:39:01 +0800114import static com.android.net.module.util.PermissionUtils.hasAnyPermissionOf;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900115import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900116
Chalard Jean5b639762020-03-09 21:25:37 +0900117import android.Manifest;
Junyu Lai71b51532024-02-01 10:39:01 +0800118import android.annotation.CheckResult;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000119import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800120import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600121import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800122import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000123import android.app.ActivityManager;
124import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800125import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800126import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700127import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700128import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900129import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800130import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700131import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800132import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133import android.content.ContentResolver;
134import android.content.Context;
135import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700136import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800137import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900138import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700139import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800140import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900141import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900142import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700143import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800144import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800145import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800146import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900147import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800148import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900149import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800150import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900151import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800152import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700153import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900154import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800155import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800157import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800158import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800159import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900160import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900161import android.net.INetworkMonitor;
162import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900163import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900164import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700165import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800166import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900167import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900168import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900169import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800170import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900171import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900172import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100173import android.net.MatchAllNetworkSpecifier;
Yang Sun29037f62023-12-04 10:31:58 +0800174import android.net.MulticastRoutingConfig;
Ken Chen6df7a902021-04-09 15:08:42 +0800175import android.net.NativeNetworkConfig;
176import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800177import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700178import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700179import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900180import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700181import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800182import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700183import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900184import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900185import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000186import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900187import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700188import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900189import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700190import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900191import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700192import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800193import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900194import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700195import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000196import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800197import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900198import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800199import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400200import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700201import android.net.QosCallbackException;
202import android.net.QosFilter;
203import android.net.QosSocketFilter;
204import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700205import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800206import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800207import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900208import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400209import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800210import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800211import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400212import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800213import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900214import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900215import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900216import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900217import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800218import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900219import android.net.networkstack.ModuleNetworkStackClient;
220import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900221import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800222import android.net.resolv.aidl.DnsHealthEventParcel;
223import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
224import android.net.resolv.aidl.Nat64PrefixEventParcel;
225import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900226import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900227import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800228import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800230import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700231import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000232import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800233import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700234import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700235import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800236import android.os.Looper;
237import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700238import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700239import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900240import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800241import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700242import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700243import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800244import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700245import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900246import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900247import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700248import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700249import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400250import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800251import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900252import android.stats.connectivity.MeteredState;
253import android.stats.connectivity.RequestType;
254import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900255import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700256import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700257import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700258import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800259import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900260import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000261import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600262import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900263import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900264import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700265import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700266import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900267import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800268
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800269import androidx.annotation.RequiresApi;
270
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900271import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400272import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400273import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700274import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900275import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900276import com.android.metrics.ConnectionDurationForTransports;
277import com.android.metrics.ConnectionDurationPerTransports;
278import com.android.metrics.ConnectivitySampleMetricsHelper;
279import com.android.metrics.ConnectivityStateSample;
280import com.android.metrics.NetworkCountForTransports;
281import com.android.metrics.NetworkCountPerTransports;
282import com.android.metrics.NetworkDescription;
283import com.android.metrics.NetworkList;
284import com.android.metrics.NetworkRequestCount;
285import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800286import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900287import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800288import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000289import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900290import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800291import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900292import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900293import com.android.net.module.util.DeviceConfigUtils;
Junyu Lai2ff42d22023-12-07 16:57:13 +0800294import com.android.net.module.util.HandlerUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100295import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900296import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
297import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900298import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800299import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800300import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100301import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000302import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800303import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
304import com.android.networkstack.apishim.ConstantsShim;
305import com.android.networkstack.apishim.common.BroadcastOptionsShim;
306import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900307import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900308import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000309import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900310import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800311import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800312import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900313import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900314import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900315import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500316import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700317import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900318import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900319import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900320import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000321import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100322import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700323import com.android.server.connectivity.MockableSystemProperties;
Yang Sun29037f62023-12-04 10:31:58 +0800324import com.android.server.connectivity.MulticastRoutingCoordinatorService;
Chalard Jean43aae652022-09-14 21:33:06 +0900325import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700326import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600327import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900328import com.android.server.connectivity.NetworkNotificationManager;
329import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900330import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900331import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900332import com.android.server.connectivity.NetworkRanker;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000333import com.android.server.connectivity.NetworkRequestStateStatsMetrics;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700334import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900335import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900336import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700337import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900338import com.android.server.connectivity.RoutingCoordinatorService;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800339import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000340import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800341import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600342
Josh Gao461a1222020-06-16 15:58:11 -0700343import libcore.io.IoUtils;
344
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900345import org.xmlpull.v1.XmlPullParserException;
346
The Android Open Source Project28527d22009-03-03 19:31:44 -0800347import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100348import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900349import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800350import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900351import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700352import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700353import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900354import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900355import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700356import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700357import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700358import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700359import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800360import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900361import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800362import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700363import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700364import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700365import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700366import java.util.Map;
Yang Sun29037f62023-12-04 10:31:58 +0800367import java.util.Map.Entry;
Chalard Jean524f0b12021-10-25 21:11:56 +0900368import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700369import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900370import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600371import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900372import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600373import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900374import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900375import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800376
377/**
378 * @hide
379 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800380public class ConnectivityService extends IConnectivityManager.Stub
381 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900382 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800383
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900384 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900385 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900386 private static final String NETWORK_ARG = "networks";
387 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800388 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900389
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900390 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900391 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
392 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800393
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900394 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700395
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100396 /**
397 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
398 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800399 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100400 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
401 * (preferably via runtime resource overlays).
402 */
403 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
404 "http://connectivitycheck.gstatic.com/generate_204";
405
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700406 // TODO: create better separation between radio types and network types
407
Robert Greenwalt2034b912009-08-12 16:08:25 -0700408 // how long to wait before switching back to a radio's default network
409 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
410 // system property that can override the above value
411 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
412 "android.telephony.apn-restore";
413
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900414 // How long to wait before putting up a "This network doesn't have an Internet connection,
415 // connect anyway?" dialog after the user selects a network that doesn't validate.
416 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
417
Chalard Jean5fb43c72022-09-08 19:03:14 +0900418 // How long to wait before considering that a network is bad in the absence of any form
419 // of connectivity (valid, partial, captive portal). If none has been detected after this
420 // delay, the stack considers this network bad, which may affect how it's handled in ranking
421 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900422 // Timeout in case the "actively prefer bad wifi" feature is on
423 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
424 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900425 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900426
junyulai0ac374f2020-12-14 18:41:52 +0800427 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900428 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
429 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800430 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700431
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800432 // Delimiter used when creating the broadcast delivery group for sending
433 // CONNECTIVITY_ACTION broadcast.
434 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
435
he_won.hwang881307a2022-03-15 21:23:52 +0900436 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900437 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900438
Daniel Brightf9e945b2020-06-15 16:10:01 -0700439 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900440 @VisibleForTesting
441 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700442
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900443 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700444 @VisibleForTesting
445 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900446
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900447 @VisibleForTesting
448 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800449 @VisibleForTesting
450 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900451 // True if the cell radio of the device is capable of time-sharing.
452 @VisibleForTesting
453 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900454
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800455 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800456 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800457 private final int mReleasePendingIntentDelayMs;
458
Chalard Jean46bfbf02022-02-02 00:56:25 +0900459 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900460
Motomu Utsumif360aa62023-01-30 17:52:20 +0900461 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700462
Chalard Jean9473c982021-07-29 20:03:04 +0900463 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800464 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700465 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800466 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700467
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900468 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700469
junyulaif2c67e42018-08-07 19:50:45 +0800470 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000471 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
472 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800473 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900474 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800475
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900476 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900477 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000478 private final int mWakeUpMark;
479 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000480 // The Context is created for UserHandle.ALL.
481 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900482 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900483 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700484 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700485 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800486
Chenbo Feng15416292018-11-08 17:36:21 -0800487 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800488 protected IDnsResolver mDnsResolver;
489 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800490 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700491 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900492 private final NetworkStatsManager mStatsManager;
493 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800494 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700495
Benedict Wong493e04b2018-11-09 14:45:34 -0800496 /**
497 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
498 * instances.
499 */
500 @GuardedBy("mTNSLock")
501 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800502 private final CompanionDeviceManagerProxyService mCdmps;
Yang Sun29037f62023-12-04 10:31:58 +0800503 private final MulticastRoutingCoordinatorService mMulticastRoutingCoordinatorService;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900504 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800505
506 private final Object mTNSLock = new Object();
507
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700508 private String mCurrentTcpBufferSizes;
509
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900510 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000511 new Class[] {
512 ConnectivityService.class,
513 NetworkAgent.class,
514 NetworkAgentInfo.class,
515 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900516
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500517 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400518 // Tear down networks that have no chance (e.g. even if validated) of becoming
519 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500520 // all networks have been rematched against all NetworkRequests.
521 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400522 // Don't reap networks. This should be passed when some networks have not yet been
523 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500524 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900525 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500526
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900527 private enum UnneededFor {
528 LINGER, // Determine whether this network is unneeded and should be lingered.
529 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
530 }
531
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700532 /**
paulhuaa0743d2021-05-26 21:56:03 +0800533 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800534 * should have priority. The order is passed to netd which will use it together
535 * with UID ranges to generate the corresponding IP rule. This serves to
536 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800537 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800538 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000539 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800540 *
paulhu48291862021-07-14 14:53:57 +0800541 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
542 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800543 */
paulhu48291862021-07-14 14:53:57 +0800544 // Used when sending to netd to code for "no order".
545 static final int PREFERENCE_ORDER_NONE = 0;
546 // Order for requests that don't code for a per-app preference. As it is
547 // out of the valid range, the corresponding order should be
548 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800549 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800550 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800551 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800552 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
553 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800554 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800555 static final int PREFERENCE_ORDER_OEM = 10;
556 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800557 // See {@link #setProfileNetworkPreference}.
558 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800559 static final int PREFERENCE_ORDER_PROFILE = 20;
560 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800561 // better scores are connected.
562 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800563 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800564 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900565 // Preference order that signifies the network shouldn't be set as a default network for
566 // the UIDs, only give them access to it. TODO : replace this with a boolean
567 // in NativeUidRangeConfig
568 @VisibleForTesting
569 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
570 // Bound for the lowest valid preference order.
571 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800572
573 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700574 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700575 * from one net to another. Clear happens when we get a new
576 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
577 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700578 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700579 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700580
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700581 /**
582 * used internally to reload global proxy settings
583 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700584 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700585
Robert Greenwalt34848c02011-03-25 13:09:25 -0700586 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400587 * PAC manager has received new port.
588 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800589 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400590
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700591 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900592 * used internally when registering NetworkProviders
593 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700594 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900595 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700596
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700597 /**
598 * used internally when registering NetworkAgents
599 * obj = Messenger
600 */
601 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
602
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700603 /**
604 * used to add a network request
605 * includes a NetworkRequestInfo
606 */
607 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
608
609 /**
610 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900611 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700612 * cancel it.
613 * includes a NetworkRequestInfo
614 */
615 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
616
617 /**
618 * used to add a network listener - no request
619 * includes a NetworkRequestInfo
620 */
621 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
622
623 /**
624 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400625 * arg1 = UID of caller
626 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700627 */
628 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
629
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700630 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900631 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700632 * obj = Messenger
633 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900634 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700635
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700636 /**
637 * used internally to expire a wakelock when transitioning
638 * from one net to another. Expire happens when we fail to find
639 * a new network (typically after 1 minute) -
640 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
641 * a replacement network.
642 */
643 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
644
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700645 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800646 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400647 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800648 */
649 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
650
651 /**
652 * used to remove a pending intent and its associated network request.
653 * arg1 = UID of caller
654 * obj = PendingIntent
655 */
656 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
657
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900658 /**
659 * used to specify whether a network should be used even if unvalidated.
660 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
661 * arg2 = whether to remember this choice in the future (1 or 0)
662 * obj = network
663 */
664 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
665
666 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700667 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900668 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700669 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900670
Paul Jensenc8873fc2015-06-17 14:15:39 -0400671 /**
672 * used to add a network listener with a pending intent
673 * obj = NetworkRequestInfo
674 */
675 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
676
Hugo Benichid6b510a2017-04-06 17:22:18 +0900677 /**
678 * used to specify whether a network should not be penalized when it becomes unvalidated.
679 */
680 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
681
682 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700683 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900684 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700685 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900686
Erik Kline31b4a9e2018-01-11 21:07:29 +0900687 // Handle changes in Private DNS settings.
688 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
689
dalyk1720e542018-03-05 12:42:22 -0500690 // Handle private DNS validation status updates.
691 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
692
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900693 /**
694 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
695 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800696 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
697 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
698 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900699 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900700 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900701
702 /**
703 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
704 * config was resolved.
705 * obj = PrivateDnsConfig
706 * arg2 = netid
707 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900708 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900709
710 /**
711 * Request ConnectivityService display provisioning notification.
712 * arg1 = Whether to make the notification visible.
713 * arg2 = NetID.
714 * obj = Intent to be launched when notification selected by user, null if !arg1.
715 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900716 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900717
718 /**
lucaslin2240ef62019-03-12 13:08:03 +0800719 * Used to specify whether a network should be used even if connectivity is partial.
720 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
721 * false)
722 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
723 * obj = network
724 */
lucaslin444d43a2020-02-20 16:56:59 +0800725 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800726
727 /**
lucasline117e2e2019-10-22 18:27:33 +0800728 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
729 * Both of the arguments are bitmasks, and the value of bits come from
730 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900731 * arg1 = unused
732 * arg2 = netId
733 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800734 */
lucaslin444d43a2020-02-20 16:56:59 +0800735 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800736
737 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900738 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
739 * arg1 = unused
740 * arg2 = netId
741 * obj = captive portal data
742 */
lucaslin444d43a2020-02-20 16:56:59 +0800743 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900744
745 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900746 * Used by setRequireVpnForUids.
747 * arg1 = whether the specified UID ranges are required to use a VPN.
748 * obj = Array of UidRange objects.
749 */
750 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
751
752 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900753 * Used internally when setting the default networks for OemNetworkPreferences.
754 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800755 */
756 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
757
758 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800759 * Used to indicate the system default network becomes active.
760 */
761 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
762
763 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900764 * Used internally when setting a network preference for a user profile.
765 * obj = Pair<ProfileNetworkPreference, Listener>
766 */
767 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
768
769 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000770 * Event to specify that reasons for why an uid is blocked changed.
771 * arg1 = uid
772 * arg2 = blockedReasons
773 */
774 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
775
776 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900777 * Event to register a new network offer
778 * obj = NetworkOffer
779 */
780 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
781
782 /**
783 * Event to unregister an existing network offer
784 * obj = INetworkOfferCallback
785 */
786 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
787
788 /**
paulhu51f77dc2021-06-07 02:34:20 +0000789 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
790 */
791 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
792
793 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800794 * Event to set temporary allow bad wifi within a limited time to override
795 * {@code config_networkAvoidBadWifi}.
796 */
797 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
798
799 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100800 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
801 */
802 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
803
804 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900805 * The initial evaluation period is over for this network.
806 *
807 * If no form of connectivity has been found on this network (valid, partial, captive portal)
808 * then the stack will now consider it to have been determined bad.
809 */
810 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
811
812 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000813 * Used internally when the user does not want the network from captive portal app.
814 * obj = Network
815 */
816 private static final int EVENT_USER_DOES_NOT_WANT = 58;
817
818 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000819 * Event to set VPN as preferred network for specific apps.
820 * obj = VpnNetworkPreferenceInfo
821 */
822 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
823
824 /**
chiachangwange0192a72023-02-06 13:25:01 +0000825 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
826 */
827 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
828
829 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000830 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
831 */
832 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
833
834 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900835 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
836 * should be shown.
837 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900838 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900839
840 /**
841 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
842 * should be hidden.
843 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900844 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900845
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800846 /**
847 * The maximum alive time to allow bad wifi configuration for testing.
848 */
849 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
850
Patrick Rohr2857ac42022-01-21 14:58:16 +0100851 /**
chiachangwange0192a72023-02-06 13:25:01 +0000852 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
853 * testing.
854 */
855 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
856
857 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100858 * The priority of the tc police rate limiter -- smaller value is higher priority.
859 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
860 */
861 private static final short TC_PRIO_POLICE = 1;
862
863 /**
864 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
865 */
866 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700867 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100868
Hugo Benichi47011212017-03-30 10:46:05 +0900869 private static String eventName(int what) {
870 return sMagicDecoderRing.get(what, Integer.toString(what));
871 }
872
paulhua10d8212020-11-10 15:32:56 +0800873 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900874 final DnsResolverServiceManager dsm = context.getSystemService(
875 DnsResolverServiceManager.class);
876 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800877 }
878
Cody Kesting73708bf2019-12-18 10:57:50 -0800879 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900880 @VisibleForTesting
881 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700882 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700883 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700884 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700885 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800886 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
887 @VisibleForTesting
888 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
889
Erik Kline32120082017-12-13 19:40:49 +0900890 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900891 @VisibleForTesting
892 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700893
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400894 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800895 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400896
Chalard Jean46bfbf02022-02-02 00:56:25 +0900897 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800898 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700899
Chalard Jean5d70ba42018-06-07 16:44:04 +0900900 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
901 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800902 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400903
Erik Kline05f2b402015-04-30 12:58:40 +0900904 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700905
Chalard Jean46bfbf02022-02-02 00:56:25 +0900906 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400907
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700908 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900909 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700910
Valentin Iftime9fa35092019-09-24 13:32:13 +0200911 private Set<String> mWolSupportedInterfaces;
912
Roshan Pius08c94fb2020-01-16 12:17:17 -0800913 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800914 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800915 private final AppOpsManager mAppOpsManager;
916
917 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400918
chiachangwang3d60bac2023-01-17 14:38:08 +0000919 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900920 private final QosCallbackTracker mQosCallbackTracker;
921 private final NetworkNotificationManager mNotifier;
922 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900923
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700924 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800925 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700926
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900927 // Sequence number for NetworkProvider IDs.
928 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
929 NetworkProvider.FIRST_PROVIDER_ID);
930
Erik Klineedf878b2015-07-09 18:24:03 +0900931 // NetworkRequest activity String log entries.
932 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
933 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
934
Hugo Benichid159fdd2016-07-11 11:05:12 +0900935 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900936 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900937 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
938
Hugo Benichi47011212017-03-30 10:46:05 +0900939 private static final int MAX_WAKELOCK_LOGS = 20;
940 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900941 private int mTotalWakelockAcquisitions = 0;
942 private int mTotalWakelockReleases = 0;
943 private long mTotalWakelockDurationMs = 0;
944 private long mMaxWakelockDurationMs = 0;
945 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900946
Hugo Benichi208c0102016-07-28 17:53:06 +0900947 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900948
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000949 @Nullable private final NetworkRequestStateStatsMetrics mNetworkRequestStateStatsMetrics;
950
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700951 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900952 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700953
Erik Kline95ecfee2016-10-02 18:02:14 +0900954 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900955 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900956
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900957 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800958 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
959 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800960
Patrick Rohr2857ac42022-01-21 14:58:16 +0100961 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
962 // configured via {@link
963 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
964 // Only the handler thread is allowed to access this field.
965 private long mIngressRateLimit = -1;
966
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900967 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
968 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900969 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900970 @GuardedBy("mSelfCertifiedCapabilityCache")
971 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
972 mSelfCertifiedCapabilityCache = new HashMap<>();
973
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900974 // Flag to enable the feature of closing frozen app sockets.
975 private final boolean mDestroyFrozenSockets;
976
977 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
978 private final boolean mDelayDestroyFrozenSockets;
979
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900980 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
981 private final boolean mAllowSysUiConnectivityReports;
982
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900983 // Uids that ConnectivityService is pending to close sockets of.
984 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
985
Robert Greenwalt802c1102014-06-02 15:32:02 -0700986 /**
987 * Implements support for the legacy "one network per network type" model.
988 *
989 * We used to have a static array of NetworkStateTrackers, one for each
990 * network type, but that doesn't work any more now that we can have,
991 * for example, more that one wifi network. This class stores all the
992 * NetworkAgentInfo objects that support a given type, but the legacy
993 * API will only see the first one.
994 *
995 * It serves two main purposes:
996 *
997 * 1. Provide information about "the network for a given type" (since this
998 * API only supports one).
999 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
1000 * the first network for a given type changes, or if the default network
1001 * changes.
1002 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001003 @VisibleForTesting
1004 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001005
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09001006 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001007 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001008
Robert Greenwalt802c1102014-06-02 15:32:02 -07001009 /**
1010 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1011 * Each list holds references to all NetworkAgentInfos that are used to
1012 * satisfy requests for that network type.
1013 *
1014 * This array is built out at startup such that an unsupported network
1015 * doesn't get an ArrayList instance, making this a tristate:
1016 * unsupported, supported but not active and active.
1017 *
1018 * The actual lists are populated when we scan the network types that
1019 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001020 *
1021 * Threading model:
1022 * - addSupportedType() is only called in the constructor
1023 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1024 * They are therefore not thread-safe with respect to each other.
1025 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1026 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001027 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001028 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001029 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001030 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001031 @NonNull
1032 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001033
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001034 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1035 // an entry have no timer (equivalent to -1). Lazily loaded.
1036 @NonNull
1037 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1038
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001039 LegacyTypeTracker(@NonNull ConnectivityService service) {
1040 mService = service;
1041 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001042 }
1043
Chiachang Wang3bc52762021-11-25 14:17:57 +08001044 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1045 // addressed.
1046 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001047 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1048 final PackageManager pm = ctx.getPackageManager();
1049 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1050 addSupportedType(TYPE_WIFI);
1051 }
1052 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1053 addSupportedType(TYPE_WIFI_P2P);
1054 }
1055 if (tm.isDataCapable()) {
1056 // Telephony does not have granular support for these types: they are either all
1057 // supported, or none is supported
1058 addSupportedType(TYPE_MOBILE);
1059 addSupportedType(TYPE_MOBILE_MMS);
1060 addSupportedType(TYPE_MOBILE_SUPL);
1061 addSupportedType(TYPE_MOBILE_DUN);
1062 addSupportedType(TYPE_MOBILE_HIPRI);
1063 addSupportedType(TYPE_MOBILE_FOTA);
1064 addSupportedType(TYPE_MOBILE_IMS);
1065 addSupportedType(TYPE_MOBILE_CBS);
1066 addSupportedType(TYPE_MOBILE_IA);
1067 addSupportedType(TYPE_MOBILE_EMERGENCY);
1068 }
1069 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1070 addSupportedType(TYPE_BLUETOOTH);
1071 }
1072 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1073 // TYPE_PROXY is only used on Wear
1074 addSupportedType(TYPE_PROXY);
1075 }
1076 // Ethernet is often not specified in the configs, although many devices can use it via
1077 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001078 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001079 addSupportedType(TYPE_ETHERNET);
1080 }
1081
1082 // Always add TYPE_VPN as a supported type
1083 addSupportedType(TYPE_VPN);
1084 }
1085
1086 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001087 if (mTypeLists[type] != null) {
1088 throw new IllegalStateException(
1089 "legacy list for type " + type + "already initialized");
1090 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001091 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001092 }
1093
Robert Greenwalt802c1102014-06-02 15:32:02 -07001094 public boolean isTypeSupported(int type) {
1095 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1096 }
1097
1098 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001099 synchronized (mTypeLists) {
1100 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1101 return mTypeLists[type].get(0);
1102 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001103 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001104 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001105 }
1106
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001107 public int getRestoreTimerForType(int type) {
1108 synchronized (mTypeLists) {
1109 if (mRestoreTimers == null) {
1110 mRestoreTimers = loadRestoreTimers();
1111 }
1112 return mRestoreTimers.getOrDefault(type, -1);
1113 }
1114 }
1115
1116 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1117 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001118 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001119 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1120 for (final String config : configs) {
1121 final String[] splits = TextUtils.split(config, ",");
1122 if (splits.length != 2) {
1123 logwtf("Invalid restore timer token count: " + config);
1124 continue;
1125 }
1126 try {
1127 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1128 } catch (NumberFormatException e) {
1129 logwtf("Invalid restore timer number format: " + config, e);
1130 }
1131 }
1132 return ret;
1133 }
1134
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001135 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001136 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001137 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001138 log("Sending " + state
1139 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001140 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001141 }
1142 }
1143
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001144 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1145 // network type, to preserve previous behaviour.
1146 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1147 if (vpnNai != mService.getLegacyLockdownNai()) return;
1148
1149 if (vpnNai.declaredUnderlyingNetworks == null
1150 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1151 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1152 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1153 return;
1154 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001155 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001156 vpnNai.declaredUnderlyingNetworks[0]);
1157 if (underlyingNai == null) return;
1158
1159 final int type = underlyingNai.networkInfo.getType();
1160 final DetailedState state = DetailedState.CONNECTED;
1161 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1162 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1163 }
1164
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001165 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001166 public void add(int type, NetworkAgentInfo nai) {
1167 if (!isTypeSupported(type)) {
1168 return; // Invalid network type.
1169 }
1170 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1171
1172 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1173 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001174 return;
1175 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001176 synchronized (mTypeLists) {
1177 list.add(nai);
1178 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001179
Chalard Jean5b409c72021-02-04 13:12:59 +09001180 // Send a broadcast if this is the first network of its type or if it's the default.
1181 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001182
1183 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1184 // to preserve previous behaviour.
1185 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001186 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001187 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1188 mService.sendLegacyNetworkBroadcast(nai, state, type);
1189 }
1190
1191 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1192 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001193 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001194 }
1195
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001196 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001197 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001198 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1199 if (list == null || list.isEmpty()) {
1200 return;
1201 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001202 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001203
Hugo Benichi389633f2016-06-21 09:48:07 +09001204 synchronized (mTypeLists) {
1205 if (!list.remove(nai)) {
1206 return;
1207 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001208 }
1209
Lorenzo Colitti49767722015-05-01 00:30:10 +09001210 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001211 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1212 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001213 }
1214
1215 if (!list.isEmpty() && wasFirstNetwork) {
1216 if (DBG) log("Other network available for type " + type +
1217 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001218 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001219 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001220 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001221 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001222 }
1223 }
1224
1225 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001226 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1227 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001228 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001229 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001230 }
1231 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001232
Chalard Jean46bfbf02022-02-02 00:56:25 +09001233 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001234 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001235 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001236 final DetailedState state = nai.networkInfo.getDetailedState();
1237 for (int type = 0; type < mTypeLists.length; type++) {
1238 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001239 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001240 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001241 if (isFirst || contains && isDefault) {
1242 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001243 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001244 }
1245 }
1246 }
1247
Robert Greenwalt94e22142014-07-30 16:31:24 -07001248 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001249 pw.println("mLegacyTypeTracker:");
1250 pw.increaseIndent();
1251 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001252 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001253 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001254 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001255 pw.println();
1256 pw.println("Current state:");
1257 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001258 synchronized (mTypeLists) {
1259 for (int type = 0; type < mTypeLists.length; type++) {
1260 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1261 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001262 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001263 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001264 }
1265 }
1266 pw.decreaseIndent();
1267 pw.decreaseIndent();
1268 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001269 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001270 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001271 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001272
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001273 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001274 /**
1275 * Helper class which parses out priority arguments and dumps sections according to their
1276 * priority. If priority arguments are omitted, function calls the legacy dump command.
1277 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001278 private class LocalPriorityDump {
1279 private static final String PRIORITY_ARG = "--dump-priority";
1280 private static final String PRIORITY_ARG_HIGH = "HIGH";
1281 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001282 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001283
1284 LocalPriorityDump() {}
1285
1286 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001287 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> {
Junyu Laif8dba342023-10-12 17:01:03 +08001288 doDump(fd, pw, new String[]{DIAG_ARG});
1289 doDump(fd, pw, new String[]{SHORT_ARG});
1290 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1291 pw.println("dumpHigh timeout");
1292 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001293 }
1294
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001295 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001296 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> doDump(fd, pw, args),
Junyu Laif8dba342023-10-12 17:01:03 +08001297 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1298 pw.println("dumpNormal timeout");
1299 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001300 }
1301
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001302 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1303 if (args == null) {
1304 dumpNormal(fd, pw, args);
1305 return;
1306 }
1307
1308 String priority = null;
1309 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1310 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1311 argIndex++;
1312 priority = args[argIndex];
1313 }
1314 }
1315
1316 if (PRIORITY_ARG_HIGH.equals(priority)) {
1317 dumpHigh(fd, pw);
1318 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1319 dumpNormal(fd, pw, args);
1320 } else {
1321 // ConnectivityService publishes binder service using publishBinderService() with
1322 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001323 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1324 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001325 // TODO: Integrate into signal dump.
1326 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001327 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001328 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001329 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001330
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001331 /**
1332 * Dependencies of ConnectivityService, for injection in tests.
1333 */
1334 @VisibleForTesting
1335 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001336 public int getCallingUid() {
1337 return Binder.getCallingUid();
1338 }
1339
Chalard Jeandf29a852023-05-29 17:02:43 +09001340 public boolean isAtLeastS() {
1341 return SdkLevel.isAtLeastS();
1342 }
1343
1344 public boolean isAtLeastT() {
1345 return SdkLevel.isAtLeastT();
1346 }
1347
1348 public boolean isAtLeastU() {
1349 return SdkLevel.isAtLeastU();
1350 }
1351
Chalard Jeaneb663892023-10-07 15:17:07 +09001352 public boolean isAtLeastV() {
1353 return SdkLevel.isAtLeastV();
1354 }
1355
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001356 /**
1357 * Get system properties to use in ConnectivityService.
1358 */
1359 public MockableSystemProperties getSystemProperties() {
1360 return new MockableSystemProperties();
1361 }
1362
1363 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001364 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1365 */
1366 public ConnectivityResources getResources(@NonNull Context ctx) {
1367 return new ConnectivityResources(ctx);
1368 }
1369
1370 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001371 * Create a HandlerThread to use in ConnectivityService.
1372 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001373 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1374 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001375 }
1376
1377 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001378 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001379 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001380 public NetworkStackClientBase getNetworkStack() {
1381 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001382 }
1383
1384 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001385 * @see ProxyTracker
1386 */
1387 public ProxyTracker makeProxyTracker(@NonNull Context context,
1388 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001389 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001390 }
1391
1392 /**
1393 * @see NetIdManager
1394 */
1395 public NetIdManager makeNetIdManager() {
1396 return new NetIdManager();
1397 }
1398
1399 /**
1400 * @see NetworkUtils#queryUserAccess(int, int)
1401 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001402 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1403 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001404 }
1405
1406 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001407 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1408 * requires CAP_NET_ADMIN, which the unit tests do not have.
1409 */
1410 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1411 InetSocketAddress remote) {
1412 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1413 }
1414
1415 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001416 * @see MultinetworkPolicyTracker
1417 */
1418 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1419 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1420 return new MultinetworkPolicyTracker(c, h, r);
1421 }
1422
Aaron Huang330a4c02020-10-27 03:36:19 +08001423 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001424 * @see AutomaticOnOffKeepaliveTracker
1425 */
1426 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1427 @NonNull Context c, @NonNull Handler h) {
1428 return new AutomaticOnOffKeepaliveTracker(c, h);
1429 }
1430
Yang Sun29037f62023-12-04 10:31:58 +08001431 public MulticastRoutingCoordinatorService makeMulticastRoutingCoordinatorService(
1432 @NonNull Handler h) {
1433 try {
1434 return new MulticastRoutingCoordinatorService(h);
1435 } catch (UnsupportedOperationException e) {
1436 // Multicast routing is not supported by the kernel
1437 Log.i(TAG, "Skipping unsupported MulticastRoutingCoordinatorService");
1438 return null;
1439 }
1440 }
1441
chiachangwang7c17c282023-02-02 05:58:59 +00001442 /**
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001443 * @see NetworkRequestStateStatsMetrics
1444 */
1445 public NetworkRequestStateStatsMetrics makeNetworkRequestStateStatsMetrics(
1446 Context context) {
1447 // We currently have network requests metric for Watch devices only
1448 if (context.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
1449 return new NetworkRequestStateStatsMetrics();
1450 } else {
1451 return null;
1452 }
1453 }
1454
1455 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001456 * @see BatteryStatsManager
1457 */
1458 public void reportNetworkInterfaceForTransports(Context context, String iface,
1459 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001460 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001461 context.getSystemService(BatteryStatsManager.class);
1462 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1463 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001464
1465 public boolean getCellular464XlatEnabled() {
1466 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1467 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001468
1469 /**
1470 * @see PendingIntent#intentFilterEquals
1471 */
1472 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1473 return a.intentFilterEquals(b);
1474 }
1475
1476 /**
1477 * @see LocationPermissionChecker
1478 */
1479 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1480 return new LocationPermissionChecker(context);
1481 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001482
1483 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001484 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001485 *
1486 * This method returns null in versions before T, where carrier privilege
1487 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001488 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001489 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001490 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1491 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001492 if (isAtLeastT()) {
Chalard Jean96ff9542023-11-02 14:24:47 +09001493 return new CarrierPrivilegeAuthenticator(context, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001494 } else {
1495 return null;
1496 }
1497 }
1498
1499 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001500 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001501 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001502 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001503 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001504 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001505
1506 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001507 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1508 */
1509 public boolean isFeatureNotChickenedOut(Context context, String name) {
1510 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1511 }
1512
1513 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001514 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001515 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001516 * @return BpfNetMaps implementation.
1517 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001518 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1519 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001520 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001521
1522 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001523 * @see ClatCoordinator
1524 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001525 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001526 public ClatCoordinator getClatCoordinator(INetd netd) {
1527 return new ClatCoordinator(
1528 new ClatCoordinator.Dependencies() {
1529 @NonNull
1530 public INetd getNetd() {
1531 return netd;
1532 }
1533 });
1534 }
1535
1536 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001537 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1538 */
1539 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1540 final InterfaceParams params = InterfaceParams.getByName(iface);
1541 if (params == null) {
1542 // the interface might have disappeared.
1543 logw("Failed to get interface params for interface " + iface);
1544 return;
1545 }
1546 try {
1547 // converting rateInBytesPerSecond from long to int is safe here because the
1548 // setting's range is limited to INT_MAX.
1549 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001550 Log.i(TAG,
1551 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001552 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1553 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1554 } catch (IOException e) {
1555 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1556 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1557 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1558 + ") failure: ", e);
1559 }
1560 }
1561
1562 /**
1563 * Wraps {@link TcUtils#tcFilterDelDev}
1564 */
1565 public void disableIngressRateLimit(String iface) {
1566 final InterfaceParams params = InterfaceParams.getByName(iface);
1567 if (params == null) {
1568 // the interface might have disappeared.
1569 logw("Failed to get interface params for interface " + iface);
1570 return;
1571 }
1572 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001573 Log.i(TAG,
1574 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001575 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1576 } catch (IOException e) {
1577 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1578 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1579 }
1580 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001581
1582 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001583 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1584 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001585 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001586 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001587 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001588 }
1589
1590 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001591 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1592 */
1593 // TODO: when available in all active branches:
1594 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1595 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1596 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1597 return BroadcastOptionsShimImpl.newInstance(options);
1598 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001599
1600 /**
1601 * Wrapper method for
1602 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1603 *
1604 * @param changeId The ID of the compatibility change in question.
1605 * @param packageName The package name of the app in question.
1606 * @param user The user that the operation is done for.
1607 * @return {@code true} if the change is enabled for the specified package.
1608 */
1609 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1610 @NonNull final UserHandle user) {
1611 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1612 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001613
1614 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001615 * As above but with a UID.
1616 * @see CompatChanges#isChangeEnabled(long, int)
1617 */
1618 public boolean isChangeEnabled(final long changeId, final int uid) {
1619 return CompatChanges.isChangeEnabled(changeId, uid);
1620 }
1621
1622 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001623 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1624 *
1625 * @param ranges target uid ranges
1626 * @param exemptUids uids to skip close socket
1627 */
1628 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1629 @NonNull final Set<Integer> exemptUids)
1630 throws SocketException, InterruptedIOException, ErrnoException {
1631 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1632 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001633
1634 /**
1635 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1636 *
1637 * @param ownerUids target uids to close sockets
1638 */
1639 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1640 throws SocketException, InterruptedIOException, ErrnoException {
1641 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1642 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001643
1644 /**
1645 * Schedule the evaluation timeout.
1646 *
1647 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1648 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1649 * of these events happen, this time will run out, after which the network is considered
1650 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1651 * on this network and considers it won't provide connectivity. In particular, that means
1652 * it's when the system prefers it to cell if it's wifi and configuration says it should
1653 * prefer bad wifi to cell.
1654 */
1655 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1656 @NonNull final Network network, final long delayMs) {
1657 handler.sendMessageDelayed(
1658 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1659 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001660 }
1661
junyulaie7c7d2a2021-01-26 15:29:15 +08001662 public ConnectivityService(Context context) {
1663 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001664 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1665 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001666 }
1667
1668 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001669 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1670 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001671 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001672
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001673 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001674 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001675 mSystemProperties = mDeps.getSystemProperties();
1676 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001677 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001678 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001679 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1680 // Pass limit - 1 to maintain backward compatibility.
1681 // TODO: Remove the workaround.
1682 mNetworkRequestCounter =
1683 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1684 mSystemNetworkRequestCounter =
1685 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001686
Hugo Benichi208c0102016-07-28 17:53:06 +09001687 mMetricsLog = logger;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001688 mNetworkRequestStateStatsMetrics = mDeps.makeNetworkRequestStateStatsMetrics(mContext);
James Mattis45d81842021-01-10 14:24:24 -08001689 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1690 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001691 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001692 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001693 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001694 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1695 mDefaultNetworkRequests.add(mDefaultRequest);
1696 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001697
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001698 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001699 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001700
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001701 // The default WiFi request is a background request so that apps using WiFi are
1702 // migrated to a better network (typically ethernet) when one comes up, instead
1703 // of staying on WiFi forever.
1704 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1705 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1706
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001707 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1708 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1709 NetworkRequest.Type.BACKGROUND_REQUEST);
1710
Chalard Jean0702f982021-09-16 21:50:07 +09001711 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1712 // TODO: Consider making the timer customizable.
1713 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1714 mCellularRadioTimesharingCapable =
1715 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1716
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001717 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1718 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1719
1720 if (SdkLevel.isAtLeastU()) {
1721 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1722 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1723 final int defaultUMarkMask = 0x80000000; // u32
1724
1725 if ((mark == 0) || (mask == 0)) {
1726 // simply treat unset/disabled as the default U value
1727 mark = defaultUMarkMask;
1728 mask = defaultUMarkMask;
1729 }
1730 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1731 // invalid device overlay settings
1732 throw new IllegalArgumentException(
1733 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1734 }
1735 }
1736
1737 mWakeUpMark = mark;
1738 mWakeUpMask = mask;
1739
Paul Hu51f816b2022-08-11 14:43:47 +00001740 mNetd = netd;
1741 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09001742 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00001743 mPermissionMonitor =
1744 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001745 mHandlerThread.start();
1746 mHandler = new InternalHandler(mHandlerThread.getLooper());
1747 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001748 mConnectivityDiagnosticsHandler =
1749 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001750
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001751 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001752 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001753
junyulaie7c7d2a2021-01-26 15:29:15 +08001754 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001755 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001756 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001757 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001758
Wink Saville32506bc2013-06-29 21:10:57 -07001759 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001760 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001761 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001762 mCarrierPrivilegeAuthenticator =
1763 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001764
Sudheer Shanka9967d462021-03-18 19:09:25 +00001765 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001766 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1767 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001768 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001769
1770 final PowerManager powerManager = (PowerManager) context.getSystemService(
1771 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001772 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001773 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001774
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001775 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1776 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001777 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001778 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001779 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001780 mProtectedNetworks.add(p);
1781 } else {
1782 if (DBG) loge("Ignoring protectedNetwork " + p);
1783 }
1784 }
1785
soma, kawata29444ae2019-05-23 09:30:40 +09001786 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1787
James Mattis02220e22021-03-13 19:27:21 -08001788 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001789 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001790 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001791 final IntentFilter userIntentFilter = new IntentFilter();
1792 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1793 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1794 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1795 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001796
James Mattis02220e22021-03-13 19:27:21 -08001797 // Listen to package add/removes for netd
1798 final IntentFilter packageIntentFilter = new IntentFilter();
1799 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1800 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1801 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1802 packageIntentFilter.addDataScheme("package");
1803 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001804 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001805
Junyu Lai38c75032023-12-04 07:52:19 +00001806 // This is needed for pre-V devices to propagate the data saver status
1807 // to the BPF map. This isn't supported before Android T because BPF maps are
1808 // unsupported, and it's also unnecessary on Android V and later versions,
1809 // as the platform code handles data saver bit updates. Additionally, checking
1810 // the initial data saver status here is superfluous because the intent won't
1811 // be sent until the system is ready.
1812 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
1813 final IntentFilter dataSaverIntentFilter =
1814 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
1815 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
1816 null /* broadcastPermission */, mHandler);
1817 }
1818
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001819 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1820 // But reading the trunk stable flags from mainline modules is not supported yet.
1821 // So enabling this feature on V+ release.
1822 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1823 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1824 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001825
Chalard Jean46bfbf02022-02-02 00:56:25 +09001826 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001827 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001828 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001829 } catch (RemoteException | ServiceSpecificException e) {
1830 loge("Error registering event listener :" + e);
1831 }
1832
Erik Kline05f2b402015-04-30 12:58:40 +09001833 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1834 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001835
chiachangwang7c17c282023-02-02 05:58:59 +00001836 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001837 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001838 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001839
1840 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001841 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001842 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1843 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001844 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001845 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1846 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001847
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001848 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001849 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001850 mNetworkRanker =
1851 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1852
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001853 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001854
Chiachang Wangc1215d32020-10-20 15:38:58 +08001855 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001856 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001857
Chalard Jean28018572020-12-21 18:36:52 +09001858 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1859 // request that doesn't allow fallback to the default network. It should never be visible
1860 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1861 // arguments like the handler or the DnsResolver.
1862 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001863 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001864 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001865 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001866 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001867 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001868 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1869 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001870
1871 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001872 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1873 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1874 // Even if it could, running on S would at least require mocking out the BPF map,
1875 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1876 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001877 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001878 mDscpPolicyTracker = new DscpPolicyTracker();
1879 }
Tyler Wear72388212021-09-09 14:49:02 -07001880 } catch (ErrnoException e) {
1881 loge("Unable to create DscpPolicyTracker");
1882 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001883
1884 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1885 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001886
Chalard Jeandf29a852023-05-29 17:02:43 +09001887 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001888 mCdmps = new CompanionDeviceManagerProxyService(context);
1889 } else {
1890 mCdmps = null;
1891 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001892
Chalard Jean2fb66f12023-08-25 12:50:37 +09001893 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
Yang Sun29037f62023-12-04 10:31:58 +08001894 mMulticastRoutingCoordinatorService =
1895 mDeps.makeMulticastRoutingCoordinatorService(mHandler);
Chalard Jean2fb66f12023-08-25 12:50:37 +09001896
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001897 mDestroyFrozenSockets = mDeps.isAtLeastU()
1898 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1899 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1900 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001901 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1902 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001903 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001904 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1905 new UidFrozenStateChangedCallback() {
1906 @Override
1907 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1908 if (uids.length != frozenStates.length) {
1909 Log.wtf(TAG, "uids has length " + uids.length
1910 + " but frozenStates has length " + frozenStates.length);
1911 return;
1912 }
1913
1914 final UidFrozenStateChangedArgs args =
1915 new UidFrozenStateChangedArgs(uids, frozenStates);
1916
1917 mHandler.sendMessage(
1918 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1919 }
1920 };
1921
1922 final ActivityManager activityManager =
1923 mContext.getSystemService(ActivityManager.class);
1924 activityManager.registerUidFrozenStateChangedCallback(
1925 (Runnable r) -> r.run(), frozenStateChangedCallback);
1926 }
Yuyang Huang41557552023-11-28 12:47:22 +09001927
1928 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
1929 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
1930 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001931 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001932
Xiao Ma0a171c02022-01-23 16:14:51 +00001933 /**
1934 * Check whether or not the device supports Ethernet transport.
1935 */
1936 public static boolean deviceSupportsEthernet(final Context context) {
1937 final PackageManager pm = context.getPackageManager();
1938 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1939 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1940 }
1941
Chalard Jean46adcf32018-04-18 20:18:38 +09001942 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001943 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1944 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001945 }
1946
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001947 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1948 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001949 final NetworkCapabilities netCap = new NetworkCapabilities();
1950 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001951 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001952 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001953 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001954 return netCap;
1955 }
1956
James Mattis45d81842021-01-10 14:24:24 -08001957 private NetworkRequest createDefaultRequest() {
1958 return createDefaultInternetRequestForTransport(
1959 TYPE_NONE, NetworkRequest.Type.REQUEST);
1960 }
1961
lucaslin3ba7cc22022-12-19 02:35:33 +00001962 private NetworkRequest createVpnRequest() {
1963 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1964 .withoutDefaultCapabilities()
1965 .addTransportType(TRANSPORT_VPN)
1966 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1967 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1968 .build();
1969 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1970 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1971 }
1972
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001973 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001974 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001975 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001976 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001977 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001978 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001979 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001980 netCap.addTransportType(transportType);
1981 }
James Mattis45d81842021-01-10 14:24:24 -08001982 return createNetworkRequest(type, netCap);
1983 }
1984
1985 private NetworkRequest createNetworkRequest(
1986 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001987 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001988 }
1989
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001990 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1991 NetworkRequest.Type type) {
1992 final NetworkCapabilities netCap = new NetworkCapabilities();
1993 netCap.clearAll();
1994 netCap.addCapability(capability);
1995 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1996 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1997 }
1998
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001999 // Used only for testing.
2000 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07002001 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002002 // changing ContentResolver to make registerContentObserver non-final).
2003 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
2004 // by subclassing SettingsObserver.
2005 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002006 void updateAlwaysOnNetworks() {
2007 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002008 }
2009
Erik Kline9a62f012018-03-21 07:18:33 -07002010 // See FakeSettingsProvider comment above.
2011 @VisibleForTesting
2012 void updatePrivateDnsSettings() {
2013 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
2014 }
2015
paulhu51f77dc2021-06-07 02:34:20 +00002016 @VisibleForTesting
2017 void updateMobileDataPreferredUids() {
2018 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
2019 }
2020
Patrick Rohr2857ac42022-01-21 14:58:16 +01002021 @VisibleForTesting
2022 void updateIngressRateLimit() {
2023 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
2024 }
2025
Aaron Huang40b52442021-06-08 04:34:24 +08002026 @VisibleForTesting
2027 void simulateUpdateProxyInfo(@Nullable final Network network,
2028 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08002029 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08002030 new Pair<>(network, proxyInfo)).sendToTarget();
2031 }
2032
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002033 private void handleAlwaysOnNetworkRequest(
2034 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002035 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002036 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002037 handleAlwaysOnNetworkRequest(networkRequest, enable);
2038 }
2039
2040 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002041 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002042 if (enable == isEnabled) {
2043 return; // Nothing to do.
2044 }
2045
2046 if (enable) {
2047 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002048 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002049 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002050 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002051 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002052 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2053 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002054 }
2055 }
2056
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002057 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002058 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2059 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2060 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2061 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002062 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2063 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002064 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002065 }
2066
paulhu51f77dc2021-06-07 02:34:20 +00002067 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002068 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002069 private void registerSettingsCallbacks() {
2070 // Watch for global HTTP proxy changes.
2071 mSettingsObserver.observe(
2072 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2073 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2074
Chalard Jean46bfbf02022-02-02 00:56:25 +09002075 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002076 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002077 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002078 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2079
Chalard Jean46bfbf02022-02-02 00:56:25 +09002080 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002081 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002082 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002083 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002084
2085 // Watch for mobile data preferred uids changes.
2086 mSettingsObserver.observe(
2087 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2088 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002089
2090 // Watch for ingress rate limit changes.
2091 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002092 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002093 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2094 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002095 }
2096
Erik Kline31b4a9e2018-01-11 21:07:29 +09002097 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002098 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2099 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002100 }
2101 }
2102
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002103 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002104 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2105 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002106 return mNextNetworkRequestId++;
2107 }
2108
junyulai74f9a8b2018-06-13 15:00:37 +08002109 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002110 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002111 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002112 if (network == null) {
2113 return null;
2114 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002115 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002116 }
2117
2118 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002119 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002120 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002121 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002122 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002123
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002124 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002125 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002126 private NetworkAgentInfo getVpnForUid(int uid) {
2127 synchronized (mNetworkForNetId) {
2128 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2129 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002130 if (nai.isVPN() && nai.everConnected()
2131 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002132 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002133 }
2134 }
2135 }
2136 return null;
2137 }
2138
Chalard Jean46bfbf02022-02-02 00:56:25 +09002139 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002140 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002141 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002142 final NetworkAgentInfo nai = getVpnForUid(uid);
2143 if (nai != null) return nai.declaredUnderlyingNetworks;
2144 return null;
2145 }
2146
Lorenzo Colittia7574052021-01-19 01:33:05 +09002147 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002148 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002149
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002150 final Network[] networks = getVpnUnderlyingNetworks(uid);
2151 if (networks != null) {
2152 // getUnderlyingNetworks() returns:
2153 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2154 // empty array => the VPN explicitly said "no default network".
2155 // non-empty array => the VPN specified one or more default networks; we use the
2156 // first one.
2157 if (networks.length > 0) {
2158 nai = getNetworkAgentInfoForNetwork(networks[0]);
2159 } else {
2160 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002161 }
2162 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002163 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002164 }
2165
2166 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002167 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002168 */
paulhu7aeba372020-12-30 00:42:19 +08002169 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2170 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002171 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002172 if (ignoreBlocked) {
2173 return false;
2174 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002175 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002176 final long ident = Binder.clearCallingIdentity();
2177 try {
2178 final boolean metered = nc == null ? true : nc.isMetered();
2179 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2180 } finally {
2181 Binder.restoreCallingIdentity(ident);
2182 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002183 }
2184
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002185 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002186 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2187 return;
2188 }
Hugo Benichi47011212017-03-30 10:46:05 +09002189 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002190 synchronized (mBlockedAppUids) {
2191 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002192 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002193 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002194 blocked = false;
2195 } else {
2196 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002197 }
2198 }
Hugo Benichi47011212017-03-30 10:46:05 +09002199 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2200 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2201 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002202 }
2203
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002204 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002205 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2206 return;
2207 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002208 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002209 final int requestId = nri.getActiveRequest() != null
2210 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002211 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002212 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002213 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002214 }
2215
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002216 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002217 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002218 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002219 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002220 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002221 @NonNull
2222 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2223 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002224 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2225 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2226 // but only exists if an app asks about them or requests them. Ensure the requesting app
2227 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002228 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002229 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2230 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2231 null /* extraInfo */);
2232 }
2233 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002234 return filtered;
2235 }
2236
2237 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2238 boolean ignoreBlocked) {
2239 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2240 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002241 }
2242
2243 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002244 * Return NetworkInfo for the active (i.e., connected) network interface.
2245 * It is assumed that at most one network is active at a time. If more
2246 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002247 * @return the info for the active network, or {@code null} if none is
2248 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002249 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002250 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002251 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002252 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002253 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002254 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002255 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2256 if (nai == null) return null;
2257 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2258 maybeLogBlockedNetworkInfo(networkInfo, uid);
2259 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002260 }
2261
Paul Jensen1f567382015-02-13 14:18:39 -05002262 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002263 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002264 public Network getActiveNetwork() {
2265 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002266 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002267 }
2268
2269 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002270 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002271 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002272 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002273 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002274 }
2275
Chalard Jean46bfbf02022-02-02 00:56:25 +09002276 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002277 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002278 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2279 if (vpnNai != null) {
2280 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2281 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2282 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002283 }
Paul Jensen1f567382015-02-13 14:18:39 -05002284 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002285
James Mattis2516da32021-01-31 17:06:19 -08002286 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002287 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2288 ignoreBlocked)) {
2289 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002290 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002291 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002292 }
2293
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002294 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002295 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002296 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002297 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002298 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2299 if (nai == null) return null;
2300 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002301 }
2302
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002303 /** Returns a NetworkInfo object for a network that doesn't exist. */
2304 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2305 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2306 getNetworkTypeName(networkType), "" /* subtypeName */);
2307 info.setIsAvailable(true);
2308 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2309 // background data is restricted.
2310 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2311 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2312 ? DetailedState.BLOCKED
2313 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002314 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2315 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002316 return info;
2317 }
2318
Lorenzo Colittia7574052021-01-19 01:33:05 +09002319 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002320 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2321 return null;
2322 }
2323 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002324 if (nai == null) {
2325 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002326 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002327 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2328 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002329 }
2330
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002331 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002332 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002333 public NetworkInfo getNetworkInfo(int networkType) {
2334 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002335 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002336 if (getVpnUnderlyingNetworks(uid) != null) {
2337 // A VPN is active, so we may need to return one of its underlying networks. This
2338 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002339 // getNetworkAgentInfoForUid.
2340 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2341 if (nai == null) return null;
2342 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2343 if (networkInfo.getType() == networkType) {
2344 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002345 }
2346 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002347 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002348 }
2349
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002350 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002351 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002352 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002353 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002354 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002355 if (nai == null) return null;
2356 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002357 }
2358
2359 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002360 public NetworkInfo[] getAllNetworkInfo() {
2361 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002362 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002363 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2364 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002365 NetworkInfo info = getNetworkInfo(networkType);
2366 if (info != null) {
2367 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002368 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002369 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002370 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002371 }
2372
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002373 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002374 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002375 public Network getNetworkForType(int networkType) {
2376 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002377 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2378 return null;
2379 }
2380 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2381 if (nai == null) {
2382 return null;
2383 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002384 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002385 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2386 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002387 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002388 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002389 }
2390
2391 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002392 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002393 public Network[] getAllNetworks() {
2394 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002395 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002396 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002397 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002398 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002399 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002400 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002401 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002402 }
2403
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002404 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002405 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002406 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002407 // The basic principle is: if an app's traffic could possibly go over a
2408 // network, without the app doing anything multinetwork-specific,
2409 // (hence, by "default"), then include that network's capabilities in
2410 // the array.
2411 //
2412 // In the normal case, app traffic only goes over the system's default
2413 // network connection, so that's the only network returned.
2414 //
2415 // With a VPN in force, some app traffic may go into the VPN, and thus
2416 // over whatever underlying networks the VPN specifies, while other app
2417 // traffic may go over the system default network (e.g.: a split-tunnel
2418 // VPN, or an app disallowed by the VPN), so the set of networks
2419 // returned includes the VPN's underlying networks and the system
2420 // default.
2421 enforceAccessPermission();
2422
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002423 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002424
James Mattis2516da32021-01-31 17:06:19 -08002425 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2426 if (!nri.isBeingSatisfied()) {
2427 continue;
2428 }
2429 final NetworkAgentInfo nai = nri.getSatisfier();
2430 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2431 if (null != nc
2432 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2433 && !result.containsKey(nai.network)) {
2434 result.put(
2435 nai.network,
2436 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002437 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002438 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2439 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002440 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002441 }
2442
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002443 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002444 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002445 if (null != networks) {
2446 for (final Network network : networks) {
2447 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2448 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002449 result.put(
2450 network,
2451 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002452 nc,
2453 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002454 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002455 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002456 }
2457 }
2458 }
2459
2460 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2461 out = result.values().toArray(out);
2462 return out;
2463 }
2464
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002465 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2466 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2467 // can call sampleConnectivityState and make the checks on it.
2468 @NonNull
2469 private StatsEvent sampleConnectivityStateToStatsEvent() {
2470 final ConnectivityStateSample sample = sampleConnectivityState();
2471 return ConnectivityStatsLog.buildStatsEvent(
2472 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2473 sample.getNetworkCountPerTransports().toByteArray(),
2474 sample.getConnectionDurationPerTransports().toByteArray(),
2475 sample.getNetworkRequestCount().toByteArray(),
2476 sample.getNetworks().toByteArray());
2477 }
2478
2479 /**
2480 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2481 *
2482 * This is used for metrics. These snapshots will be sampled and constitute a base for
2483 * statistics about connectivity state of devices.
2484 */
2485 @VisibleForTesting
2486 @NonNull
2487 public ConnectivityStateSample sampleConnectivityState() {
2488 ensureRunningOnConnectivityServiceThread();
2489 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2490 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2491 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2492 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2493 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2494 return builder.build();
2495 }
2496
2497 private static NetworkCountPerTransports sampleNetworkCount(
2498 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2499 final SparseIntArray countPerTransports = new SparseIntArray();
2500 for (final NetworkAgentInfo nai : nais) {
2501 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2502 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2503 }
2504 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2505 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2506 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2507 c.setTransportTypes(countPerTransports.keyAt(i));
2508 c.setNetworkCount(countPerTransports.valueAt(i));
2509 builder.addNetworkCountForTransports(c);
2510 }
2511 return builder.build();
2512 }
2513
2514 private static ConnectionDurationPerTransports sampleConnectionDuration(
2515 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2516 final ConnectionDurationPerTransports.Builder builder =
2517 ConnectionDurationPerTransports.newBuilder();
2518 for (final NetworkAgentInfo nai : nais) {
2519 final ConnectionDurationForTransports.Builder c =
2520 ConnectionDurationForTransports.newBuilder();
2521 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2522 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2523 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2524 // Add millisPerSecond/2 to round up or down to the nearest value
2525 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2526 builder.addConnectionDurationForTransports(c);
2527 }
2528 return builder.build();
2529 }
2530
2531 private static NetworkRequestCount sampleNetworkRequestCount(
2532 @NonNull final Collection<NetworkRequestInfo> nris) {
2533 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2534 final SparseIntArray countPerType = new SparseIntArray();
2535 for (final NetworkRequestInfo nri : nris) {
2536 final int type;
2537 if (Process.SYSTEM_UID == nri.mAsUid) {
2538 // The request is filed "as" the system, so it's the system on its own behalf.
2539 type = RequestType.RT_SYSTEM.getNumber();
2540 } else if (Process.SYSTEM_UID == nri.mUid) {
2541 // The request is filed by the system as some other app, so it's the system on
2542 // behalf of an app.
2543 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2544 } else {
2545 // Not the system, so it's an app requesting on its own behalf.
2546 type = RequestType.RT_APP.getNumber();
2547 }
2548 countPerType.put(type, countPerType.get(type, 0));
2549 }
2550 for (int i = countPerType.size() - 1; i >= 0; --i) {
2551 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2552 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2553 r.setRequestCount(countPerType.valueAt(i));
2554 builder.addRequestCountForType(r);
2555 }
2556 return builder.build();
2557 }
2558
2559 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2560 final NetworkList.Builder builder = NetworkList.newBuilder();
2561 for (final NetworkAgentInfo nai : nais) {
2562 final NetworkCapabilities nc = nai.networkCapabilities;
2563 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2564 d.setTransportTypes((int) nc.getTransportTypesInternal());
2565 final MeteredState meteredState;
2566 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2567 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2568 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2569 meteredState = MeteredState.METERED_NO;
2570 } else {
2571 meteredState = MeteredState.METERED_YES;
2572 }
2573 d.setMeteredState(meteredState);
2574 final ValidatedState validatedState;
2575 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2576 validatedState = ValidatedState.VS_PORTAL;
2577 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2578 validatedState = ValidatedState.VS_PARTIAL;
2579 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2580 validatedState = ValidatedState.VS_VALID;
2581 } else {
2582 validatedState = ValidatedState.VS_INVALID;
2583 }
2584 d.setValidatedState(validatedState);
2585 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2586 d.setCapabilities(nc.getCapabilitiesInternal());
2587 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2588 builder.addNetworkDescription(d);
2589 }
2590 return builder.build();
2591 }
2592
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002593 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002594 public boolean isNetworkSupported(int networkType) {
2595 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002596 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002597 }
2598
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002599 /**
2600 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002601 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002602 * @return the ip properties for the active network, or {@code null} if
2603 * none is active
2604 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002605 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002606 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002607 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002608 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002609 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2610 if (nai == null) return null;
2611 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002612 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002613 }
2614
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002615 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002616 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002617 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002618 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002619 final LinkProperties lp = getLinkProperties(nai);
2620 if (lp == null) return null;
2621 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002622 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002623 }
2624
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002625 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002626 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002627 public LinkProperties getLinkProperties(Network network) {
2628 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002629 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2630 if (lp == null) return null;
2631 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002632 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002633 }
2634
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002635 @Nullable
2636 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002637 if (nai == null) {
2638 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002639 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002640 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002641 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002642 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002643 }
2644
lucaslinc582d502022-01-27 09:07:00 +08002645 @Override
2646 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002647 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002648 @NonNull String packageName, @Nullable String callingAttributionTag) {
2649 Objects.requireNonNull(packageName);
2650 Objects.requireNonNull(lp);
2651 enforceNetworkStackOrSettingsPermission();
Junyu Lai71b51532024-02-01 10:39:01 +08002652 if (!hasAccessPermission(-1 /* pid */, uid)) {
lucaslinc582d502022-01-27 09:07:00 +08002653 return null;
2654 }
2655 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2656 }
2657
Qingxi Lib2748102020-01-08 12:51:49 -08002658 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2659 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2660 }
2661
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002662 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002663 if (nai == null) return null;
2664 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002665 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002666 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002667 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002668 }
2669
2670 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002671 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2672 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002673 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002674 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002675 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002676 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002677 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002678 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002679 }
2680
lucaslinc582d502022-01-27 09:07:00 +08002681 @Override
lucaslind2b06132022-03-02 10:56:57 +08002682 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2683 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2684 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002685 Objects.requireNonNull(nc);
2686 Objects.requireNonNull(packageName);
2687 enforceNetworkStackOrSettingsPermission();
Junyu Lai71b51532024-02-01 10:39:01 +08002688 if (!hasAccessPermission(-1 /* pid */, uid)) {
lucaslinc582d502022-01-27 09:07:00 +08002689 return null;
2690 }
2691 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2692 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2693 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2694 callingAttributionTag);
2695 }
2696
lucaslin69e1aa92022-03-22 18:15:09 +08002697 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2698 if (nc.getUnderlyingNetworks() != null
Junyu Lai71b51532024-02-01 10:39:01 +08002699 && !hasNetworkFactoryOrSettingsPermission(pid, uid)) {
lucaslin69e1aa92022-03-22 18:15:09 +08002700 nc.setUnderlyingNetworks(null);
2701 }
2702 }
2703
Chalard Jean53017782022-11-24 17:13:44 +09002704 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
2705 return Process.SYSTEM_UID == uid
Junyu Lai71b51532024-02-01 10:39:01 +08002706 || hasAnyPermissionOf(mContext, pid, uid,
Chalard Jean53017782022-11-24 17:13:44 +09002707 android.Manifest.permission.NETWORK_FACTORY);
2708 }
2709
Qingxi Libb8da982020-01-17 17:54:27 -08002710 @VisibleForTesting
2711 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002712 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002713 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2714 // this would be expensive (one more permission check every time any NC callback is
2715 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2716 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2717 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002718 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Junyu Lai71b51532024-02-01 10:39:01 +08002719 if (!hasSettingsPermission(callerPid, callerUid)) {
Chalard Jean46adcf32018-04-18 20:18:38 +09002720 newNc.setUids(null);
2721 newNc.setSSID(null);
2722 }
Etan Cohen107ae952018-12-30 17:59:59 -08002723 if (newNc.getNetworkSpecifier() != null) {
2724 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2725 }
Junyu Lai71b51532024-02-01 10:39:01 +08002726 if (!hasAnyPermissionOf(mContext, callerPid, callerUid,
Junyu Lai4c6fe232023-04-11 11:33:46 +08002727 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002728 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2729 newNc.setAdministratorUids(new int[0]);
2730 }
Chalard Jean53017782022-11-24 17:13:44 +09002731 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09002732 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002733 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002734 }
lucaslin69e1aa92022-03-22 18:15:09 +08002735 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002736
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002737 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002738 }
2739
Roshan Pius98f59ec2021-02-23 08:47:39 -08002740 /**
2741 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002742 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002743 * NetworkCapabilities.
2744 * Note: This wrapper does not support any sort of invalidation and thus must not be
2745 * persistent or long-lived. It may only be used for the time necessary to
2746 * compute the redactions required by one particular NetworkCallback or
2747 * synchronous call.
2748 */
2749 private class RedactionPermissionChecker {
2750 private final int mCallingPid;
2751 private final int mCallingUid;
2752 @NonNull private final String mCallingPackageName;
2753 @Nullable private final String mCallingAttributionTag;
2754
2755 private Boolean mHasLocationPermission = null;
2756 private Boolean mHasLocalMacAddressPermission = null;
2757 private Boolean mHasSettingsPermission = null;
2758
2759 RedactionPermissionChecker(int callingPid, int callingUid,
2760 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2761 mCallingPid = callingPid;
2762 mCallingUid = callingUid;
2763 mCallingPackageName = callingPackageName;
2764 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002765 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002766
2767 private boolean hasLocationPermissionInternal() {
2768 final long token = Binder.clearCallingIdentity();
2769 try {
2770 return mLocationPermissionChecker.checkLocationPermission(
2771 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2772 null /* message */);
2773 } finally {
2774 Binder.restoreCallingIdentity(token);
2775 }
2776 }
2777
2778 /**
2779 * Returns whether the app holds location permission or not (might return cached result
2780 * if the permission was already checked before).
2781 */
2782 public boolean hasLocationPermission() {
2783 if (mHasLocationPermission == null) {
2784 // If there is no cached result, perform the check now.
2785 mHasLocationPermission = hasLocationPermissionInternal();
2786 }
2787 return mHasLocationPermission;
2788 }
2789
2790 /**
2791 * Returns whether the app holds local mac address permission or not (might return cached
2792 * result if the permission was already checked before).
2793 */
Junyu Lai71b51532024-02-01 10:39:01 +08002794 @CheckResult
Roshan Pius98f59ec2021-02-23 08:47:39 -08002795 public boolean hasLocalMacAddressPermission() {
2796 if (mHasLocalMacAddressPermission == null) {
2797 // If there is no cached result, perform the check now.
Junyu Lai71b51532024-02-01 10:39:01 +08002798 mHasLocalMacAddressPermission = ConnectivityService.this
2799 .hasLocalMacAddressPermission(mCallingPid, mCallingUid);
Roshan Pius98f59ec2021-02-23 08:47:39 -08002800 }
2801 return mHasLocalMacAddressPermission;
2802 }
2803
2804 /**
2805 * Returns whether the app holds settings permission or not (might return cached
2806 * result if the permission was already checked before).
2807 */
Junyu Lai71b51532024-02-01 10:39:01 +08002808 @CheckResult
Roshan Pius98f59ec2021-02-23 08:47:39 -08002809 public boolean hasSettingsPermission() {
2810 if (mHasSettingsPermission == null) {
2811 // If there is no cached result, perform the check now.
Junyu Lai71b51532024-02-01 10:39:01 +08002812 mHasSettingsPermission =
2813 ConnectivityService.this.hasSettingsPermission(mCallingPid, mCallingUid);
Roshan Pius98f59ec2021-02-23 08:47:39 -08002814 }
2815 return mHasSettingsPermission;
2816 }
2817 }
2818
2819 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2820 @NetworkCapabilities.NetCapability long redaction) {
2821 return (redactions & redaction) != 0;
2822 }
2823
2824 /**
2825 * Use the provided |applicableRedactions| to check the receiving app's
2826 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2827 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2828 * before being sent to the corresponding app.
2829 */
2830 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2831 @NetworkCapabilities.RedactionType long applicableRedactions,
2832 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2833 boolean includeLocationSensitiveInfo) {
2834 long redactions = applicableRedactions;
2835 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2836 if (includeLocationSensitiveInfo
2837 && redactionPermissionChecker.hasLocationPermission()) {
2838 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2839 }
2840 }
2841 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2842 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2843 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2844 }
2845 }
2846 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2847 if (redactionPermissionChecker.hasSettingsPermission()) {
2848 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2849 }
2850 }
2851 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002852 }
2853
Qingxi Lib2748102020-01-08 12:51:49 -08002854 @VisibleForTesting
2855 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002856 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002857 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002858 int callingPid, int callingUid, @NonNull String callingPkgName,
2859 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002860 if (nc == null) {
2861 return null;
2862 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002863 // Avoid doing location permission check if the transport info has no location sensitive
2864 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002865 final RedactionPermissionChecker redactionPermissionChecker =
2866 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2867 callingAttributionTag);
2868 final long redactions = retrieveRequiredRedactions(
2869 nc.getApplicableRedactions(), redactionPermissionChecker,
2870 includeLocationSensitiveInfo);
2871 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002872 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002873 // TODO : calling UID is redacted because apps should generally not know what UID is
2874 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002875 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002876 newNc.setOwnerUid(INVALID_UID);
2877 return newNc;
2878 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002879 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2880 if (nc.hasTransport(TRANSPORT_VPN)) {
2881 // Owner UIDs already checked above. No need to re-check.
2882 return newNc;
2883 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002884 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2885 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002886 // compatibility for older apps.
2887 if (!includeLocationSensitiveInfo
2888 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002889 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002890 newNc.setOwnerUid(INVALID_UID);
2891 return newNc;
2892 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002893 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002894 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002895 newNc.setOwnerUid(INVALID_UID);
2896 }
Qingxi Lib2748102020-01-08 12:51:49 -08002897 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002898 }
2899
lucaslinc582d502022-01-27 09:07:00 +08002900 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002901 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2902 LinkProperties lp, int callerPid, int callerUid) {
2903 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002904 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2905 // this would be expensive (one more permission check every time any LP callback is
2906 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2907 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2908 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002909
2910 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2911 final boolean needsSanitization =
2912 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2913 if (!needsSanitization) {
2914 return new LinkProperties(lp);
2915 }
2916
Junyu Lai71b51532024-02-01 10:39:01 +08002917 if (hasSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002918 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002919 }
2920
2921 final LinkProperties newLp = new LinkProperties(lp);
2922 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2923 // object gets parceled.
2924 newLp.setCaptivePortalApiUrl(null);
2925 newLp.setCaptivePortalData(null);
2926 return newLp;
2927 }
2928
Roshan Pius08c94fb2020-01-16 12:17:17 -08002929 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2930 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002931 // There is no need to track the effective UID of the request here. If the caller
2932 // lacks the settings permission, the effective UID is the same as the calling ID.
Junyu Lai71b51532024-02-01 10:39:01 +08002933 if (!hasSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002934 // Unprivileged apps can only pass in null or their own UID.
2935 if (nc.getUids() == null) {
2936 // If the caller passes in null, the callback will also match networks that do not
2937 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2938 // In this case, redact everything in the request immediately. This ensures that the
2939 // app is not able to get any redacted information by filing an unredacted request
2940 // and observing whether the request matches something.
2941 if (nc.getNetworkSpecifier() != null) {
2942 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2943 }
2944 } else {
2945 nc.setSingleUid(callerUid);
2946 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002947 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002948 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002949 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002950
2951 // Clear owner UID; this can never come from an app.
2952 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002953 }
2954
Chalard Jean38354d12018-03-20 19:13:57 +09002955 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002956 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002957 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2958 }
2959 }
2960
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002961 @Override
2962 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2963 enforceAccessPermission();
2964 final int callerUid = Binder.getCallingUid();
2965 final long token = Binder.clearCallingIdentity();
2966 try {
2967 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2968 } finally {
2969 Binder.restoreCallingIdentity(token);
2970 }
2971 }
2972
junyulaiebd15162021-03-03 12:09:05 +08002973 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002974 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002975 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002976 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002977 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002978
Serik Beketayev05130302021-01-15 16:47:25 -08002979 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002980 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002981 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2982 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002983 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002984 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002985 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002986 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2987 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002988 }
2989 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002990 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002991 }
2992
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002993 @Override
junyulaiebd15162021-03-03 12:09:05 +08002994 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002995 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002996 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002997 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002998
2999 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
3000 for (Network network : getAllNetworks()) {
3001 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09003002 final boolean includeNetwork = (nai != null) && nai.isCreated();
3003 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08003004 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
3005 // NetworkCapabilities, which may contain UIDs of apps to which the
3006 // network applies. Should the UIDs be cleared so as not to leak or
3007 // interfere ?
3008 result.add(nai.getNetworkStateSnapshot());
3009 }
3010 }
3011 return result;
3012 }
3013
3014 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003015 public boolean isActiveNetworkMetered() {
3016 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003017
Qingxi Lib2748102020-01-08 12:51:49 -08003018 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06003019 if (caps != null) {
3020 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3021 } else {
3022 // Always return the most conservative value
3023 return true;
3024 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07003025 }
3026
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003027 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09003028 * Ensures that the system cannot call a particular method.
3029 */
3030 private boolean disallowedBecauseSystemCaller() {
3031 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07003032 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
3033 // for devices launched with Q and above. However, existing devices upgrading to Q and
3034 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003035 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07003036 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003037 log("This method exists only for app backwards compatibility"
3038 + " and must not be called by system services.");
3039 return true;
3040 }
3041 return false;
3042 }
3043
3044 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003045 * Ensure that a network route exists to deliver traffic to the specified
3046 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003047 * @param networkType the type of the network over which traffic to the
3048 * specified host is to be routed
3049 * @param hostAddress the IP address of the host to which the route is
3050 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003051 * @return {@code true} on success, {@code false} on failure
3052 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003053 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003054 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3055 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003056 if (disallowedBecauseSystemCaller()) {
3057 return false;
3058 }
Junyu Lai8fdc4312024-01-16 11:19:43 +08003059 PermissionUtils.enforcePackageNameMatchesUid(
3060 mContext, mDeps.getCallingUid(), callingPackageName);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003061 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003062 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003063 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003064 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003065
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003066 InetAddress addr;
3067 try {
3068 addr = InetAddress.getByAddress(hostAddress);
3069 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003070 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003071 return false;
3072 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003073
The Android Open Source Project28527d22009-03-03 19:31:44 -08003074 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003075 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003076 return false;
3077 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003078
3079 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3080 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003081 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003082 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3083 } else {
3084 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3085 }
3086 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003087 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003088
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003089 DetailedState netState;
3090 synchronized (nai) {
3091 netState = nai.networkInfo.getDetailedState();
3092 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003093
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003094 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003095 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003096 log("requestRouteToHostAddress on down network "
3097 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003098 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003099 }
3100 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003101 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003102
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003103 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003104 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003105 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003106 LinkProperties lp;
3107 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003108 synchronized (nai) {
3109 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003110 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003111 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003112 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003113 if (DBG) {
3114 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3115 }
Wink Saville32506bc2013-06-29 21:10:57 -07003116 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003117 } finally {
3118 Binder.restoreCallingIdentity(token);
3119 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003120 }
3121
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003122 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003123 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003124 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003125 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003126 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003127 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003128 if (bestRoute.getGateway().equals(addr)) {
3129 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003130 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003131 } else {
3132 // if we will connect to this through another route, add a direct route
3133 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003134 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003135 }
3136 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003137 if (DBG) log("Adding legacy route " + bestRoute +
3138 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003139
3140 final String dst = bestRoute.getDestinationLinkAddress().toString();
3141 final String nextHop = bestRoute.hasGateway()
3142 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003143 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003144 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3145 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003146 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003147 return false;
3148 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003149 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003150 }
3151
paulhu7c0a2e62021-01-08 00:51:49 +08003152 class DnsResolverUnsolicitedEventCallback extends
3153 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003154 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003155 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003156 try {
3157 mHandler.sendMessage(mHandler.obtainMessage(
3158 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003159 new PrivateDnsValidationUpdate(event.netId,
3160 InetAddresses.parseNumericAddress(event.ipAddress),
3161 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003162 } catch (IllegalArgumentException e) {
3163 loge("Error parsing ip address in validation event");
3164 }
3165 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003166
3167 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003168 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3169 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003170 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3171 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3172 // event callback for certain nai. e.g. cellular. Register here to pass to
3173 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003174 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003175 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3176 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003177 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003178 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003179 }
3180 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003181
3182 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003183 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3184 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3185 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003186 }
dalyk1720e542018-03-05 12:42:22 -05003187
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003188 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003189 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003190 return this.VERSION;
3191 }
3192
3193 @Override
3194 public String getInterfaceHash() {
3195 return this.HASH;
3196 }
paulhu7c0a2e62021-01-08 00:51:49 +08003197 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003198
3199 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003200 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3201 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003202
paulhu7c0a2e62021-01-08 00:51:49 +08003203 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003204 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003205 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003206 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003207 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003208 }
3209 }
3210
Sudheer Shanka9967d462021-03-18 19:09:25 +00003211 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003212 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003213 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003214 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3215 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003216 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003217 };
3218
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003219 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003220 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003221 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003222 }
3223
Mark Fasheh7c999d82023-05-04 20:23:11 +00003224 static final class UidFrozenStateChangedArgs {
3225 final int[] mUids;
3226 final int[] mFrozenStates;
3227
3228 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3229 mUids = uids;
3230 mFrozenStates = frozenStates;
3231 }
3232 }
3233
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003234 /**
3235 * Check if the cell network is idle.
3236 * @return true if the cell network state is idle
3237 * false if the cell network state is active or unknown
3238 */
3239 private boolean isCellNetworkIdle() {
3240 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3241 if (defaultNai == null
3242 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3243 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3244 // cell network is not the default network, cell network state is unknown.
3245 // TODO(b/279380356): Track cell network state when the cell is not the default network
3246 return false;
3247 }
3248
3249 return !mNetworkActivityTracker.isDefaultNetworkActive();
3250 }
3251
Mark Fasheh7c999d82023-05-04 20:23:11 +00003252 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003253 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003254
3255 for (int i = 0; i < uids.length; i++) {
3256 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003257 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003258 } else {
3259 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003260 }
3261 }
3262
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003263 if (ownerUids.isEmpty()) {
3264 return;
3265 }
3266
3267 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3268 // Delay closing sockets to avoid waking the cell modem up.
3269 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3270 // than waking cell modem up.
3271 mPendingFrozenUids.addAll(ownerUids);
3272 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003273 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003274 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003275 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003276 loge("Exception in socket destroy: " + e);
3277 }
3278 }
3279 }
3280
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003281 private void closePendingFrozenSockets() {
3282 ensureRunningOnConnectivityServiceThread();
3283
3284 try {
3285 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3286 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3287 loge("Failed to close pending frozen app sockets: " + e);
3288 }
3289 mPendingFrozenUids.clear();
3290 }
3291
3292 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3293 mNetworkActivityTracker.handleReportNetworkActivity(params);
3294
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003295 final boolean isCellNetworkActivity;
3296 if (mTrackMultiNetworkActivities) {
3297 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3298 // nai could be null if netd receives a netlink message and calls the network
3299 // activity change callback after the network is unregistered from ConnectivityService.
3300 isCellNetworkActivity = nai != null
3301 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3302 } else {
3303 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3304 }
3305
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003306 if (mDelayDestroyFrozenSockets
3307 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003308 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003309 && !mPendingFrozenUids.isEmpty()) {
3310 closePendingFrozenSockets();
3311 }
3312 }
3313
3314 /**
3315 * If the cellular network is no longer the default network, close pending frozen sockets.
3316 *
3317 * @param newNetwork new default network
3318 * @param oldNetwork old default network
3319 */
3320 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3321 NetworkAgentInfo oldNetwork) {
3322 final boolean isOldNetworkCellular = oldNetwork != null
3323 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3324 final boolean isNewNetworkCellular = newNetwork != null
3325 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3326
3327 if (isOldNetworkCellular
3328 && !isNewNetworkCellular
3329 && !mPendingFrozenUids.isEmpty()) {
3330 closePendingFrozenSockets();
3331 }
3332 }
3333
3334 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3335 pw.println("CloseFrozenAppSockets:");
3336 pw.increaseIndent();
3337 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3338 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3339 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3340 pw.decreaseIndent();
3341 }
3342
Junyu Lai155760b2023-10-05 14:51:00 +08003343 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3344 pw.println("Bpf Program Status:");
3345 pw.increaseIndent();
3346 try {
3347 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003348 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003349 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003350 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003351 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003352 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003353 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003354 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003355 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003356 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003357 } catch (IOException e) {
3358 pw.println(" IOException");
3359 }
3360 pw.decreaseIndent();
3361 }
3362
Mark Fasheh7c999d82023-05-04 20:23:11 +00003363 @VisibleForTesting
3364 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003365 @VisibleForTesting
3366 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3367 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003368
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003369 @VisibleForTesting
3370 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3371 "allow_sysui_connectivity_reports";
3372
Yuyang Huang41557552023-11-28 12:47:22 +09003373 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
3374
Paul Jensen83f5d572014-08-29 09:54:01 -04003375 private void enforceInternetPermission() {
3376 mContext.enforceCallingOrSelfPermission(
3377 android.Manifest.permission.INTERNET,
3378 "ConnectivityService");
3379 }
3380
The Android Open Source Project28527d22009-03-03 19:31:44 -08003381 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003382 mContext.enforceCallingOrSelfPermission(
3383 android.Manifest.permission.ACCESS_NETWORK_STATE,
3384 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003385 }
3386
Junyu Lai71b51532024-02-01 10:39:01 +08003387 @CheckResult
3388 private boolean hasAccessPermission(int pid, int uid) {
lucaslinc582d502022-01-27 09:07:00 +08003389 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3390 == PERMISSION_GRANTED;
3391 }
3392
paulhua6ee2122021-02-22 15:40:43 +08003393 /**
3394 * Performs a strict and comprehensive check of whether a calling package is allowed to
3395 * change the state of network, as the condition differs for pre-M, M+, and
3396 * privileged/preinstalled apps. The caller is expected to have either the
3397 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3398 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3399 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3400 * permission and cannot be revoked. See http://b/23597341
3401 *
3402 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3403 * of this app will be updated to the current time.
3404 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003405 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003406 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3407 == PackageManager.PERMISSION_GRANTED) {
3408 return;
3409 }
3410
3411 if (callingPkg == null) {
3412 throw new SecurityException("Calling package name is null.");
3413 }
3414
3415 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3416 final int uid = mDeps.getCallingUid();
3417 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3418 callingPkg, callingAttributionTag, null /* message */);
3419
3420 if (mode == AppOpsManager.MODE_ALLOWED) {
3421 return;
3422 }
3423
3424 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3425 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3426 return;
3427 }
3428
3429 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3430 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3431 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003432 }
3433
Charles He9369e612017-05-15 17:07:18 +01003434 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003435 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003436 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003437 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003438 }
3439
Quang Luong98858d62023-02-11 00:25:24 +00003440 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003441 enforceAnyPermissionOf(mContext,
3442 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003443 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003444 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3445 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3446 }
3447
paulhu8e96a752019-08-12 16:25:11 +08003448 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003449 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003450 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003451 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003452 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003453 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003454 }
3455
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003456 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003457 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003458 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003459 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003460 android.Manifest.permission.NETWORK_SETTINGS,
3461 android.Manifest.permission.NETWORK_FACTORY,
3462 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3463 }
3464
3465 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003466 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003467 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003468 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003469 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3470 android.Manifest.permission.NETWORK_FACTORY,
3471 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3472 }
3473
Junyu Lai71b51532024-02-01 10:39:01 +08003474 @CheckResult
3475 private boolean hasNetworkFactoryOrSettingsPermission(int pid, int uid) {
lucaslin69e1aa92022-03-22 18:15:09 +08003476 return PERMISSION_GRANTED == mContext.checkPermission(
3477 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3478 || PERMISSION_GRANTED == mContext.checkPermission(
3479 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3480 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003481 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003482 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003483 }
3484
Junyu Lai71b51532024-02-01 10:39:01 +08003485 @CheckResult
3486 private boolean hasSettingsPermission() {
3487 return hasAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003488 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003489 }
3490
Junyu Lai71b51532024-02-01 10:39:01 +08003491 @CheckResult
3492 private boolean hasSettingsPermission(int pid, int uid) {
Chalard Jean9a396cc2018-02-21 18:43:54 +09003493 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003494 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3495 || PERMISSION_GRANTED == mContext.checkPermission(
3496 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003497 }
3498
paulhu8e96a752019-08-12 16:25:11 +08003499 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003500 enforceNetworkStackPermissionOr(mContext,
3501 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003502 }
3503
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003504 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003505 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003506 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003507 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003508 }
3509
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003510 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003511 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003512 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3513 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003514 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003515 }
3516
James Mattis8378aec2021-01-26 14:05:36 -08003517 private void enforceOemNetworkPreferencesPermission() {
3518 mContext.enforceCallingOrSelfPermission(
3519 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3520 "ConnectivityService");
3521 }
3522
James Mattisfa270db2021-05-31 17:11:10 -07003523 private void enforceManageTestNetworksPermission() {
3524 mContext.enforceCallingOrSelfPermission(
3525 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3526 "ConnectivityService");
3527 }
3528
Junyu Lai71b51532024-02-01 10:39:01 +08003529 @CheckResult
3530 private boolean hasNetworkStackPermission() {
3531 return hasAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003532 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003533 }
3534
Junyu Lai71b51532024-02-01 10:39:01 +08003535 @CheckResult
3536 private boolean hasNetworkStackPermission(int pid, int uid) {
3537 return hasAnyPermissionOf(mContext, pid, uid, android.Manifest.permission.NETWORK_STACK,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003538 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3539 }
3540
Junyu Lai71b51532024-02-01 10:39:01 +08003541 @CheckResult
3542 private boolean hasSystemBarServicePermission(int pid, int uid) {
3543 return hasAnyPermissionOf(mContext, pid, uid,
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003544 android.Manifest.permission.STATUS_BAR_SERVICE);
3545 }
3546
Junyu Lai71b51532024-02-01 10:39:01 +08003547 @CheckResult
3548 private boolean hasNetworkSignalStrengthWakeupPermission(int pid, int uid) {
3549 return hasAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003550 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003551 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3552 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003553 }
3554
Junyu Lai71b51532024-02-01 10:39:01 +08003555 @CheckResult
3556 private boolean hasConnectivityRestrictedNetworksPermission(int callingUid,
Paul Hu8fc2a552022-05-04 18:44:42 +08003557 boolean checkUidsAllowedList) {
Junyu Lai71b51532024-02-01 10:39:01 +08003558 if (hasAnyPermissionOf(mContext,
Paul Hu8fc2a552022-05-04 18:44:42 +08003559 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3560 return true;
3561 }
3562
3563 // fallback to ConnectivityInternalPermission
3564 // TODO: Remove this fallback check after all apps have declared
3565 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
Junyu Lai71b51532024-02-01 10:39:01 +08003566 if (hasAnyPermissionOf(mContext, android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003567 return true;
3568 }
3569
3570 // Check whether uid is in allowed on restricted networks list.
3571 if (checkUidsAllowedList
3572 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3573 return true;
3574 }
3575 return false;
3576 }
3577
3578 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3579 final int callingUid = mDeps.getCallingUid();
Junyu Lai71b51532024-02-01 10:39:01 +08003580 if (!hasConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003581 throw new SecurityException("ConnectivityService: user " + callingUid
3582 + " has no permission to access restricted network.");
3583 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003584 }
3585
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003586 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003587 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003588 }
3589
Junyu Lai71b51532024-02-01 10:39:01 +08003590 @CheckResult
3591 private boolean hasLocalMacAddressPermission(int pid, int uid) {
Roshan Pius98f59ec2021-02-23 08:47:39 -08003592 return PERMISSION_GRANTED == mContext.checkPermission(
3593 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3594 }
3595
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003596 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003597 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003598 }
3599
3600 private void sendInetConditionBroadcast(NetworkInfo info) {
3601 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3602 }
3603
Wink Saville4f0de1e2011-08-04 15:01:58 -07003604 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003605 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003606 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003607 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003608 if (info.isFailover()) {
3609 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3610 info.setFailover(false);
3611 }
3612 if (info.getReason() != null) {
3613 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3614 }
3615 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003616 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3617 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003618 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003619 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003620 return intent;
3621 }
3622
3623 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3624 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3625 }
3626
Michael Groover73f69482023-01-27 11:01:25 -06003627 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3628 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003629 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3630 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003631 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003632 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003633 if (!mSystemReady
3634 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003635 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003636 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003637 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003638 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003639 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003640 }
3641
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003642 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003643 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003644 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003645 final NetworkInfo ni = intent.getParcelableExtra(
3646 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003647 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3648 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003649 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003650 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003651 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003652 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003653 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003654 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003655 } finally {
3656 Binder.restoreCallingIdentity(ident);
3657 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003658 }
3659 }
3660
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003661 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3662 NetworkInfo info) {
3663 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003664 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003665
3666 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3667 try {
3668 // This allows us to discard older broadcasts still waiting to be delivered
3669 // which have the same namespace and key.
3670 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3671 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3672 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003673 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003674 } catch (UnsupportedApiLevelException e) {
3675 Log.wtf(TAG, "Using unsupported API" + e);
3676 }
3677 }
3678
3679 @VisibleForTesting
3680 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3681 final StringBuilder sb = new StringBuilder();
3682 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3683 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3684 sb.append(info.getExtraInfo());
3685 return sb.toString();
3686 }
3687
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003688 /**
Aaron Huang96011892020-06-27 07:18:23 +08003689 * Called by SystemServer through ConnectivityManager when the system is ready.
3690 */
3691 @Override
3692 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003693 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003694 throw new SecurityException("Calling Uid is not system uid.");
3695 }
3696 systemReadyInternal();
3697 }
3698
3699 /**
3700 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003701 */
3702 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003703 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003704 // Load flags after PackageManager is ready to query module version
3705 mFlags.loadFlags(mDeps, mContext);
3706
Aaron Huang9a57acf2020-12-08 10:03:29 +08003707 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3708 // listening network request which is sent by MultipathPolicyTracker won't be added
3709 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3710 // be called after PermissionMonitor#startMonitoring().
3711 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3712 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3713 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003714 final ConditionVariable startMonitoringDone = new ConditionVariable();
3715 mHandler.post(() -> {
3716 mPermissionMonitor.startMonitoring();
3717 startMonitoringDone.open();
3718 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003719 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003720 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003721
Hugo Benichie5220992017-04-26 14:53:28 +09003722 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003723 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003724 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003725 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003726 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003727 }
3728 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003729
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003730 // Create network requests for always-on networks.
3731 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003732
3733 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003734 // Note that updating can be skipped here if the list is empty only because no uid
3735 // rules are applied before system ready. Normally, the empty uid list means to clear
3736 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003737 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3738 updateMobileDataPreferredUids();
3739 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003740
3741 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003742 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003743 mBpfNetMaps.setPullAtomCallback(mContext);
3744 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003745 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3746 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003747 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3748 // have permission problem. While CV#block() is unbounded in time and can in principle block
3749 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3750 // could have blocked forever too.
3751 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003752 }
3753
The Android Open Source Project28527d22009-03-03 19:31:44 -08003754 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003755 * Start listening for default data network activity state changes.
3756 */
3757 @Override
3758 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003759 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003760 }
3761
3762 /**
3763 * Stop listening for default data network activity state changes.
3764 */
3765 @Override
3766 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003767 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003768 }
3769
3770 /**
3771 * Check whether the default network radio is currently active.
3772 */
3773 @Override
3774 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003775 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003776 }
3777
3778 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003779 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003780 * and set it on it's iface.
3781 */
Junyu Lai970963e2022-10-25 15:46:47 +08003782 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003783 final String iface = newLp.getInterfaceName();
3784 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003785 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003786 // Silently ignore unset MTU value.
3787 return;
3788 }
Hansen Kurli04252032022-12-07 11:21:49 +00003789 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3790 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3791 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003792 return;
3793 }
Hansen Kurli04252032022-12-07 11:21:49 +00003794 // Cannot set MTU without interface name
3795 if (TextUtils.isEmpty(iface)) {
3796 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003797 return;
3798 }
sy.yun4aa73922013-09-02 05:24:09 +09003799
Hansen Kurli04252032022-12-07 11:21:49 +00003800 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3801 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003802 return;
3803 }
3804
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003805 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003806 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003807 mNetd.interfaceSetMtu(iface, mtu);
3808 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003809 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003810 }
3811 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003812
Chenbo Feng15416292018-11-08 17:36:21 -08003813 @VisibleForTesting
3814 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003815
Junyu Lai970963e2022-10-25 15:46:47 +08003816 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003817 String[] values = null;
3818 if (tcpBufferSizes != null) {
3819 values = tcpBufferSizes.split(",");
3820 }
3821
3822 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003823 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003824 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3825 values = tcpBufferSizes.split(",");
3826 }
3827
3828 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3829
3830 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003831 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003832
Chenbo Feng15416292018-11-08 17:36:21 -08003833 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3834 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3835 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003836 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003837 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003838 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003839 }
3840 }
3841
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003842 @Override
3843 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003844 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003845 NETWORK_RESTORE_DELAY_PROP_NAME);
3846 if(restoreDefaultNetworkDelayStr != null &&
3847 restoreDefaultNetworkDelayStr.length() != 0) {
3848 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003849 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003850 } catch (NumberFormatException e) {
3851 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003852 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003853 // if the system property isn't set, use the value for the apn type
3854 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3855
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003856 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3857 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003858 }
3859 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003860 }
3861
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003862 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003863 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003864 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003865 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003866 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003867 // Start gathering diagnostic information.
3868 netDiags.add(new NetworkDiagnostics(
3869 nai.network,
3870 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003871 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003872 DIAG_TIME_MS));
3873 }
3874
3875 for (NetworkDiagnostics netDiag : netDiags) {
3876 pw.println();
3877 netDiag.waitForMeasurements();
3878 netDiag.dump(pw);
3879 }
3880 }
3881
The Android Open Source Project28527d22009-03-03 19:31:44 -08003882 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003883 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3884 @Nullable String[] args) {
Junyu Lai71b51532024-02-01 10:39:01 +08003885 if (!hasDumpPermission(mContext, TAG, writer)) return;
Chiachang Wanga101f852021-04-19 10:59:24 +08003886
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003887 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003888 }
3889
Junyu Lai71b51532024-02-01 10:39:01 +08003890 @CheckResult
3891 private boolean hasDumpPermission(Context context, String tag, PrintWriter pw) {
lucaslin99473f62020-12-10 15:10:54 +08003892 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3893 != PackageManager.PERMISSION_GRANTED) {
3894 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003895 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003896 + " due to missing android.permission.DUMP permission");
3897 return false;
3898 } else {
3899 return true;
3900 }
3901 }
3902
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003903 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003904 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003905
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003906 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003907 dumpNetworkDiagnostics(pw);
3908 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003909 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003910 dumpNetworks(pw);
3911 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003912 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003913 dumpNetworkRequests(pw);
3914 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003915 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3916 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3917 dumpTrafficController(pw, fd, verbose);
3918 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003919 }
Erik Kline9647f382015-06-05 17:47:34 +09003920
Junyu Lai0da479b2022-04-20 15:06:29 +08003921 pw.println("NetworkProviders for:");
3922 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003923 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003924 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003925 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003926 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003927 pw.println();
3928
Chalard Jean5b409c72021-02-04 13:12:59 +09003929 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003930 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003931 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003932 pw.println("none");
3933 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003934 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003935 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003936 pw.println();
3937
James Mattis8b298a02021-06-01 22:34:04 -07003938 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003939 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003940 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003941 pw.decreaseIndent();
3942 pw.println();
3943
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003944 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003945 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003946 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003947 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003948 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003949
junyulaif2c67e42018-08-07 19:50:45 +08003950 pw.println("Status for known UIDs:");
3951 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003952 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003953 for (int i = 0; i < size; i++) {
3954 // Don't crash if the array is modified while dumping in bugreports.
3955 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003956 final int uid = mUidBlockedReasons.keyAt(i);
3957 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3958 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003959 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003960 } catch (ArrayIndexOutOfBoundsException e) {
3961 pw.println(" ArrayIndexOutOfBoundsException");
3962 } catch (ConcurrentModificationException e) {
3963 pw.println(" ConcurrentModificationException");
3964 }
3965 }
3966 pw.println();
3967 pw.decreaseIndent();
3968
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003969 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003970 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003971 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003972 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003973 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003974
Junyu Lai0da479b2022-04-20 15:06:29 +08003975 pw.println("Network Offers:");
3976 pw.increaseIndent();
3977 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3978 pw.println(offerInfo.offer);
3979 }
3980 pw.decreaseIndent();
3981 pw.println();
3982
Robert Greenwalt94e22142014-07-30 16:31:24 -07003983 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003984
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003985 pw.println();
markchien5e866652019-09-30 14:40:57 +08003986 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003987
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003988 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003989 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003990
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003991 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003992 dumpCloseFrozenAppSockets(pw);
3993
3994 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003995 dumpBpfProgramStatus(pw);
3996
Chalard Jean53017782022-11-24 17:13:44 +09003997 if (null != mCarrierPrivilegeAuthenticator) {
3998 pw.println();
3999 mCarrierPrivilegeAuthenticator.dump(pw);
4000 }
4001
Junyu Lai155760b2023-10-05 14:51:00 +08004002 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004003
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004004 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004005 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09004006 pw.println("mNetworkRequestInfoLogs (most recent first):");
4007 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004008 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09004009 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09004010
4011 pw.println();
4012 pw.println("mNetworkInfoBlockingLogs (most recent first):");
4013 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004014 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09004015 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09004016
4017 pw.println();
4018 pw.println("NetTransition WakeLock activity (most recent first):");
4019 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004020 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
4021 pw.println("total releases: " + mTotalWakelockReleases);
4022 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
4023 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
4024 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4025 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4026 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4027 }
James Mattiscb1e0362021-04-06 17:07:42 -07004028 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004029
4030 pw.println();
4031 pw.println("bandwidth update requests (by uid):");
4032 pw.increaseIndent();
4033 synchronized (mBandwidthRequests) {
4034 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4035 pw.println("[" + mBandwidthRequests.keyAt(i)
4036 + "]: " + mBandwidthRequests.valueAt(i));
4037 }
4038 }
4039 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004040 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004041
James Mattiscb1e0362021-04-06 17:07:42 -07004042 pw.println();
4043 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4044 pw.increaseIndent();
4045 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004046 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004047 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004048
4049 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004050
4051 pw.println();
4052 pw.println("Permission Monitor:");
4053 pw.increaseIndent();
4054 mPermissionMonitor.dump(pw);
4055 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004056
4057 pw.println();
4058 pw.println("Legacy network activity:");
4059 pw.increaseIndent();
4060 mNetworkActivityTracker.dump(pw);
4061 pw.decreaseIndent();
Yang Sunca537d52024-01-19 12:53:50 +08004062
4063 pw.println();
4064 pw.println("Multicast routing supported: " +
4065 (mMulticastRoutingCoordinatorService != null));
The Android Open Source Project28527d22009-03-03 19:31:44 -08004066 }
4067
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004068 private void dumpNetworks(IndentingPrintWriter pw) {
4069 for (NetworkAgentInfo nai : networksSortedById()) {
4070 pw.println(nai.toString());
4071 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004072 pw.println("Nat464Xlat:");
4073 pw.increaseIndent();
4074 nai.dumpNat464Xlat(pw);
4075 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004076 pw.println(String.format(
4077 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4078 nai.numForegroundNetworkRequests(),
4079 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4080 nai.numBackgroundNetworkRequests(),
4081 nai.numNetworkRequests()));
4082 pw.increaseIndent();
4083 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4084 pw.println(nai.requestAt(i).toString());
4085 }
4086 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004087 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004088 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004089 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004090 pw.decreaseIndent();
4091 pw.decreaseIndent();
4092 }
4093 }
4094
James Mattis8b298a02021-06-01 22:34:04 -07004095 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4096 if (!mProfileNetworkPreferences.isEmpty()) {
4097 pw.println("Profile preferences:");
4098 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004099 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004100 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004101 }
James Mattis8b298a02021-06-01 22:34:04 -07004102 if (!mOemNetworkPreferences.isEmpty()) {
4103 pw.println("OEM preferences:");
4104 pw.increaseIndent();
4105 pw.println(mOemNetworkPreferences);
4106 pw.decreaseIndent();
4107 }
4108 if (!mMobileDataPreferredUids.isEmpty()) {
4109 pw.println("Mobile data preferred UIDs:");
4110 pw.increaseIndent();
4111 pw.println(mMobileDataPreferredUids);
4112 pw.decreaseIndent();
4113 }
James Mattis45d81842021-01-10 14:24:24 -08004114
James Mattis8b298a02021-06-01 22:34:04 -07004115 pw.println("Default requests:");
4116 pw.increaseIndent();
4117 dumpPerAppDefaultRequests(pw);
4118 pw.decreaseIndent();
4119 }
4120
4121 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004122 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4123 if (mDefaultRequest == defaultRequest) {
4124 continue;
4125 }
4126
James Mattis8b298a02021-06-01 22:34:04 -07004127 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4128 final String networkOutput;
4129 if (null == satisfier) {
4130 networkOutput = "null";
4131 } else if (mNoServiceNetwork.equals(satisfier)) {
4132 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004133 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004134 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004135 }
James Mattis8b298a02021-06-01 22:34:04 -07004136 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4137 ? "" : " asUid: " + defaultRequest.mAsUid;
4138 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4139 + defaultRequest.mPid + asUidString + "]";
4140 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4141 + " Preference order: " + defaultRequest.mPreferenceOrder
4142 + " Tracked UIDs: " + defaultRequest.getUids();
4143 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004144 }
4145 }
4146
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004147 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004148 NetworkRequestInfo[] infos = null;
4149 while (infos == null) {
4150 try {
4151 infos = requestsSortedById();
4152 } catch (ConcurrentModificationException e) {
4153 // mNetworkRequests should only be accessed from handler thread, except dump().
4154 // As dump() is never called in normal usage, it would be needlessly expensive
4155 // to lock the collection only for its benefit. Instead, retry getting the
4156 // requests if ConcurrentModificationException is thrown during dump().
4157 }
4158 }
4159 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004160 pw.println(nri.toString());
4161 }
4162 }
4163
Ken Chene6d511f2022-01-25 11:10:42 +08004164 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4165 boolean verbose) {
4166 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004167 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004168 } catch (ServiceSpecificException e) {
4169 pw.println(e.getMessage());
4170 } catch (IOException e) {
4171 loge("Dump BPF maps failed, " + e);
4172 }
4173 }
4174
Chalard Jean524f0b12021-10-25 21:11:56 +09004175 private void dumpAllRequestInfoLogsToLogcat() {
4176 try (PrintWriter logPw = new PrintWriter(new Writer() {
4177 @Override
4178 public void write(final char[] cbuf, final int off, final int len) {
4179 // This method is called with 0-length and 1-length arrays for empty strings
4180 // or strings containing only the DEL character.
4181 if (len <= 1) return;
4182 Log.e(TAG, new String(cbuf, off, len));
4183 }
4184 @Override public void flush() {}
4185 @Override public void close() {}
4186 })) {
4187 mNetworkRequestInfoLogs.dump(logPw);
4188 }
4189 }
4190
Hugo Benichia480ba52018-09-03 08:19:02 +09004191 /**
4192 * Return an array of all current NetworkAgentInfos sorted by network id.
4193 */
4194 private NetworkAgentInfo[] networksSortedById() {
4195 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004196 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004197 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004198 return networks;
4199 }
4200
4201 /**
4202 * Return an array of all current NetworkRequest sorted by request id.
4203 */
James Mattis258ea3c2020-11-15 15:04:40 -08004204 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004205 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004206 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004207 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004208 // Sort the array based off the NRI containing the min requestId in its requests.
4209 Arrays.sort(requests,
4210 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4211 Comparator.comparingInt(req -> req.requestId)).requestId
4212 )
4213 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004214 return requests;
4215 }
4216
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004217 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004218 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004219 if (officialNai != null && officialNai.equals(nai)) return true;
4220 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004221 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004222 " - " + nai);
4223 }
4224 return false;
4225 }
4226
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004227 private boolean isDisconnectRequest(Message msg) {
4228 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4229 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4230 return info.getState() == NetworkInfo.State.DISCONNECTED;
4231 }
4232
Robert Greenwalt2034b912009-08-12 16:08:25 -07004233 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004234 private class NetworkStateTrackerHandler extends Handler {
4235 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004236 super(looper);
4237 }
4238
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004239 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004240 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4241 final NetworkAgentInfo nai = arg.first;
4242 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004243 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004244 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004245 }
4246 return;
4247 }
4248
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004249 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004250 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004251 return;
4252 }
4253
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004254 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004255 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004256 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4257 if (!nai.respectsNcStructuralConstraints(proposed)) {
4258 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4259 + nai.networkCapabilities + " -> " + proposed);
4260 disconnectAndDestroyNetwork(nai);
4261 return;
4262 }
4263 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004264 final NetworkCapabilities sanitized =
4265 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004266 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004267 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004268 break;
4269 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004270 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004271 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004272 processLinkPropertiesFromAgent(nai, newLp);
4273 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004274 break;
4275 }
4276 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004277 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004278 updateNetworkInfo(nai, info);
4279 break;
4280 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004281 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4282 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004283 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004284 break;
4285 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004286 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004287 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004288 break;
4289 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004290 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004291 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004292 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004293 // Note that if the NAI had been connected, this would affect the
4294 // score, and therefore would require re-mixing the score and performing
4295 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004296 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004297 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4298 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004299 // Mark the network as temporarily accepting partial connectivity so that it
4300 // will be validated (and possibly become default) even if it only provides
4301 // partial internet access. Note that if user connects to partial connectivity
4302 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4303 // out of wifi coverage) and if the same wifi is available again, the device
4304 // will auto connect to this wifi even though the wifi has "no internet".
4305 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004306 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004307 break;
4308 }
junyulai011b1f12019-01-03 18:50:15 +08004309 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004310 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004311 break;
4312 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004313 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004314 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004315 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004316
4317 if (isLegacyLockdownNai(nai)
4318 && (underlying == null || underlying.size() != 1)) {
4319 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4320 + " must have exactly one underlying network: " + underlying);
4321 }
4322
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004323 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4324 nai.declaredUnderlyingNetworks = (underlying != null)
4325 ? underlying.toArray(new Network[0]) : null;
4326
4327 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4328 if (DBG) {
4329 log(nai.toShortString() + " changed underlying networks to "
4330 + Arrays.toString(nai.declaredUnderlyingNetworks));
4331 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004332 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004333 notifyIfacesChangedForNetworkStats();
4334 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004335 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004336 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004337 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4338 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4339 nai.teardownDelayMs = msg.arg1;
4340 } else {
4341 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4342 }
Chalard Jean550b5212021-03-05 23:07:53 +09004343 break;
4344 }
4345 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4346 nai.setLingerDuration((int) arg.second);
4347 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004348 }
Tyler Wear72388212021-09-09 14:49:02 -07004349 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4350 DscpPolicy policy = (DscpPolicy) arg.second;
4351 if (mDscpPolicyTracker != null) {
4352 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4353 }
4354 break;
4355 }
4356 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4357 if (mDscpPolicyTracker != null) {
4358 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4359 }
4360 break;
4361 }
4362 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4363 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004364 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004365 }
4366 break;
4367 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004368 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004369 if (!nai.everConnected()) {
4370 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4371 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004372 teardownUnneededNetwork(nai);
4373 break;
4374 }
4375
4376 if (nai.isDestroyed()) {
4377 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4378 + ", ignoring");
4379 break;
4380 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004381
4382 final int timeoutMs = (int) arg.second;
4383 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4384 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4385 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4386 }
4387
4388 // Marking a network awaiting replacement is used to ensure that any requests
4389 // satisfied by the network do not switch to another network until a
4390 // replacement is available or the wait for a replacement times out.
4391 // If the network is inactive (i.e., nascent or lingering), then there are no
4392 // such requests, and there is no point keeping it. Just tear it down.
4393 // Note that setLingerDuration(0) cannot be used to do this because the network
4394 // could be nascent.
4395 nai.clearInactivityState();
4396 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4397 Log.d(TAG, nai.toShortString()
4398 + " marked awaiting replacement is unneeded, tearing down instead");
4399 teardownUnneededNetwork(nai);
4400 break;
4401 }
4402
4403 Log.d(TAG, "Marking " + nai.toShortString()
4404 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4405 destroyNativeNetwork(nai);
4406
4407 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4408 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4409 // consider the fact that the network could already have disconnected or been
4410 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4411 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4412 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4413 mKeepaliveTracker.handleStopAllKeepalives(nai,
4414 SocketKeepalive.ERROR_INVALID_NETWORK);
4415
4416 nai.updateScoreForNetworkAgentUpdate();
4417 // This rematch is almost certainly not going to result in any changes, because
4418 // the destroyed flag is only just above the "current satisfier wins"
4419 // tie-breaker. But technically anything that affects scoring should rematch.
4420 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004421 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004422 break;
4423 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004424 }
4425 }
4426
4427 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004428 final int netId = msg.arg2;
4429 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004430 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004431 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004432 switch (msg.what) {
4433 default:
4434 return false;
lucasline117e2e2019-10-22 18:27:33 +08004435 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004436 if (nai == null) {
4437 break;
4438 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004439 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4440 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004441 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004442 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004443 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004444 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004445 if (probePrivateDnsCompleted) {
4446 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4447 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004448 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004449 }
4450 // Only show the notification when the private DNS is broken and the
4451 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004452 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004453 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4454 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004455 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004456 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4457 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4458 // private DNS is broken, it means this network is being reevaluated.
4459 // Either probing private DNS is not necessary any more or it hasn't been
4460 // done yet. In either case, the networkCapabilities should be updated to
4461 // reflect the new status.
4462 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004463 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004464 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004465 }
4466 break;
4467 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004468 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004469 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4470
Erik Kline31b4a9e2018-01-11 21:07:29 +09004471 if (nai == null) break;
4472
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004473 handleNetworkTested(nai, results.mTestResult,
4474 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004475 break;
4476 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004477 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004478 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004479 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004480 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004481 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004482 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004483 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4484 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004485 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004486 if (nai == null) {
4487 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4488 break;
4489 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004490 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004491 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004492 (PendingIntent) msg.obj,
4493 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004494 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004495 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004496 break;
4497 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004498 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004499 if (nai == null) break;
4500
Erik Kline9a62f012018-03-21 07:18:33 -07004501 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004502 break;
4503 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004504 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004505 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004506 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004507 break;
4508 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004509 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004510 return true;
4511 }
4512
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004513 private void handleNetworkTested(
4514 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004515 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4516 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004517 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004518
4519 // If there is any kind of working networking, then the NAI has been evaluated
4520 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4521 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004522 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004523 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004524 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4525 // any callback that receives onAvailable for that rematch receives an extra caps
4526 // callback. To prevent that, update the score in the agent so the updates below won't
4527 // see an update to both caps and score at the same time.
4528 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004529 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4530
he_won.hwang881307a2022-03-15 21:23:52 +09004531 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4532 // Assume the validation failure is due to a temporary failure after roaming
4533 // and ignore it. NetworkMonitor will continue to retry validation. If it
4534 // continues to fail after the block timeout expires, the network will be
4535 // marked unvalidated. If it succeeds, then validation state will not change.
4536 return;
4537 }
4538
Chalard Jean254bd162022-08-25 13:04:51 +09004539 final boolean wasValidated = nai.isValidated();
4540 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004541 final boolean wasPortal = nai.captivePortalDetected();
4542 nai.setPartialConnectivity(partial);
4543 nai.setCaptivePortalDetected(portal);
4544 nai.updateScoreForNetworkAgentUpdate();
4545 final boolean partialConnectivityChanged = (wasPartial != partial);
4546 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004547
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004548 if (DBG) {
4549 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4550 ? " with redirect to " + redirectUrl
4551 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004552 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004553 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004554 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004555 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004556 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004557 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004558 if (valid) {
4559 handleFreshlyValidatedNetwork(nai);
4560 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4561 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004562 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004563 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004564 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004565 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004566 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004567 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004568 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004569 NotificationType.PRIVATE_DNS_BROKEN);
4570 // If network becomes valid, the hasShownBroken should be reset for
4571 // that network so that the notification will be fired when the private
4572 // DNS is broken again.
4573 nai.networkAgentConfig.hasShownBroken = false;
4574 }
4575 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004576 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004577 } else if (portalChanged) {
4578 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004579 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004580 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4581 nai.onPreventAutomaticReconnect();
4582 teardownUnneededNetwork(nai);
4583 return;
4584 } else {
4585 updateCapabilitiesForNetwork(nai);
4586 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004587 } else if (becameEvaluated) {
4588 // If valid or partial connectivity changed, updateCapabilities* has
4589 // done the rematch.
4590 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004591 }
4592 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004593
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004594 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004595 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004596 nai.onValidationStatusChanged(
4597 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4598 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004599
4600 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004601 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004602 // immediately. Re-notify partial connectivity silently if no internet
4603 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004604 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004605 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004606 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4607 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004608 }
4609
Chalard Jean254bd162022-08-25 13:04:51 +09004610 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004611 handleNetworkUnvalidated(nai);
4612 }
4613 }
4614
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004615 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4616 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4617 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4618 // Do not avoid captive portal when network is wear proxy.
4619 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4620 }
4621
Calvin Ondada1452016-10-11 15:10:46 -07004622 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004623 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4624 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004625 }
4626
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004627 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4628 switch (msg.what) {
4629 default:
4630 return false;
4631 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4632 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4633 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4634 handleLingerComplete(nai);
4635 }
4636 break;
4637 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004638 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4639 handleNetworkAgentRegistered(msg);
4640 break;
4641 }
4642 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4643 handleNetworkAgentDisconnected(msg);
4644 break;
4645 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004646 }
4647 return true;
4648 }
4649
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004650 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004651 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004652 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004653 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004654 maybeHandleNetworkAgentMessage(msg);
4655 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004656 }
4657 }
4658
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004659 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004660 private final int mNetId;
4661 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004662
4663 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004664 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004665 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004666 }
4667
4668 @Override
4669 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4670 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004671 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004672 }
4673
4674 @Override
4675 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004676 // Legacy version of notifyNetworkTestedWithExtras.
4677 // Would only be called if the system has a NetworkStack module older than the
4678 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004679 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004680 }
4681
4682 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004683 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004684 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4685 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004686 final Message msg = mTrackerHandler.obtainMessage(
4687 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004688 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004689 new NetworkTestedResults(
4690 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004691 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004692
4693 // Invoke ConnectivityReport generation for this Network test event.
4694 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4695 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004696
Cody Kestingf1120be2020-08-03 18:01:40 -07004697 // NetworkMonitor reports the network validation result as a bitmask while
4698 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4699 // logical value for ConnectivityDiagnostics.
4700 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4701 p.result);
4702
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004703 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004704 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004705 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4706 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4707
Aaron Huang959d3642021-01-21 15:47:41 +08004708 ConnectivityReportEvent reportEvent =
4709 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4710 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004711 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004712 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004713 }
4714
4715 @Override
4716 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4717 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4718 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004719 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004720 }
4721
4722 @Override
lucasline117e2e2019-10-22 18:27:33 +08004723 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4724 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4725 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004726 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004727 }
4728
4729 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004730 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4731 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4732 EVENT_CAPPORT_DATA_CHANGED,
4733 0, mNetId, data));
4734 }
4735
4736 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004737 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004738 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004739 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004740
4741 final PendingIntent pendingIntent;
4742 // Only the system server can register notifications with package "android"
4743 final long token = Binder.clearCallingIdentity();
4744 try {
paulhu7746e4e2020-06-09 19:07:03 +08004745 pendingIntent = PendingIntent.getBroadcast(
4746 mContext,
4747 0 /* requestCode */,
4748 intent,
4749 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004750 } finally {
4751 Binder.restoreCallingIdentity(token);
4752 }
4753 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4754 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004755 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004756 }
4757
4758 @Override
4759 public void hideProvisioningNotification() {
4760 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004761 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004762 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004763
4764 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004765 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004766 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004767 }
4768
4769 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004770 public int getInterfaceVersion() {
4771 return this.VERSION;
4772 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004773
4774 @Override
4775 public String getInterfaceHash() {
4776 return this.HASH;
4777 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004778 }
4779
Cody Kestingf1120be2020-08-03 18:01:40 -07004780 /**
4781 * Converts the given NetworkMonitor-specific validation result bitmask to a
4782 * ConnectivityDiagnostics-specific validation result int.
4783 */
4784 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4785 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4786 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4787 }
4788 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4789 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4790 }
4791 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4792 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4793 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4794 }
4795
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004796 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004797 log("Data stall detected with methods: " + p.detectionMethod);
4798
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004799 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004800 int detectionMethod = 0;
4801 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4802 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4803 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4804 }
4805 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4806 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4807 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4808 p.tcpMetricsCollectionPeriodMillis);
4809 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004810 }
4811
Cody Kestingf53a0752020-04-15 12:33:28 -07004812 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004813 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004814 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004815
4816 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4817 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4818 // the cost of going through two handlers.
4819 mConnectivityDiagnosticsHandler.sendMessage(msg);
4820 }
4821
Cody Kestingb37958e2020-05-15 10:36:01 -07004822 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4823 return (p.detectionMethod & detectionMethod) != 0;
4824 }
4825
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004826 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4827 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004828 }
4829
Erik Klinea73af002018-06-26 18:53:43 +09004830 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4831 if (nai == null) return;
4832 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4833 // in order to restart a validation pass from within netd.
4834 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00004835 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004836 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004837 }
4838 }
4839
Erik Kline31b4a9e2018-01-11 21:07:29 +09004840 private void handlePrivateDnsSettingsChanged() {
4841 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4842
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004843 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004844 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004845 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004846 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4847 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004848 }
4849 }
4850
Erik Kline9a62f012018-03-21 07:18:33 -07004851 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4852 // Private DNS only ever applies to networks that might provide
4853 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004854 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004855
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004856 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004857 // schedule DNS resolutions. If a DNS resolution is required the
4858 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004859 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004860
4861 // With Private DNS bypass support, we can proceed to update the
4862 // Private DNS config immediately, even if we're in strict mode
4863 // and have not yet resolved the provider name into a set of IPs.
4864 updatePrivateDns(nai, cfg);
4865 }
4866
4867 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4868 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004869 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004870 }
4871
dalyk1720e542018-03-05 12:42:22 -05004872 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4873 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4874 if (nai == null) {
4875 return;
4876 }
4877 mDnsManager.updatePrivateDnsValidation(update);
4878 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4879 }
4880
paulhu7c0a2e62021-01-08 00:51:49 +08004881 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004882 int prefixLength) {
4883 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4884 if (nai == null) return;
4885
paulhu7c0a2e62021-01-08 00:51:49 +08004886 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4887 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004888
4889 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004890 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004891 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004892 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004893 prefixLength);
4894 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004895 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004896 return;
4897 }
4898 }
4899
Lorenzo Colittid523d142020-04-01 20:16:30 +09004900 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004901 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4902 }
4903
Hai Shalome58bdc62021-01-11 18:45:34 -08004904 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004905 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004906 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004907 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4908 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4909 }
4910
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004911 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004912 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004913 * @param nai the agent info to update
4914 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004915 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004916 */
junyulai2b6f0c22021-02-03 20:15:30 +08004917 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4918 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4919 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004920 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004921 // one lingered request, set inactive.
4922 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004923 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004924 if (DBG) log("Unsetting inactive " + nai.toShortString());
4925 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004926 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004927 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004928 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004929 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4930 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004931 }
junyulai2b6f0c22021-02-03 20:15:30 +08004932 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004933 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004934 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004935 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004936 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004937 }
4938
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004939 private void handleNetworkAgentRegistered(Message msg) {
4940 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4941 if (!mNetworkAgentInfos.contains(nai)) {
4942 return;
4943 }
4944
4945 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4946 if (VDBG) log("NetworkAgent registered");
4947 } else {
4948 loge("Error connecting NetworkAgent");
4949 mNetworkAgentInfos.remove(nai);
4950 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004951 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004952 synchronized (mNetworkForNetId) {
4953 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004954 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004955 mNetIdManager.releaseNetId(nai.network.getNetId());
4956 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004957 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004958 }
4959 }
4960 }
Paul Jensend5f53392014-11-25 15:26:53 -05004961
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004962 @VisibleForTesting
4963 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004964 // The feature of creating the networks immediately was slated for U, but race conditions
4965 // detected late required this was flagged off.
4966 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4967 // in NetworkAgentTest.
4968 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004969 }
4970
4971 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4972 @NonNull NetworkInfo.State state) {
4973 if (nai.isCreated()) return false;
4974 if (state == NetworkInfo.State.CONNECTED) return true;
4975 if (state != NetworkInfo.State.CONNECTING) {
4976 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004977 if (shouldCreateNetworksImmediately()) {
4978 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4979 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004980 return false;
4981 }
4982 return nai.isVPN() || shouldCreateNetworksImmediately();
4983 }
4984
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004985 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004986 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004987 }
4988
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004989 @VisibleForTesting
4990 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004991 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004992 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004993
4994 // If the network never roamed, return false. The check below is not sufficient if time
4995 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4996 if (nai.lastRoamTime == 0) return false;
4997
he_won.hwang881307a2022-03-15 21:23:52 +09004998 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4999 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005000 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09005001 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09005002 final long currentTimeMs = SystemClock.elapsedRealtime();
5003 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09005004 if (timeSinceLastRoam <= blockTimeOut) {
5005 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
5006 return true;
5007 }
5008 }
5009 return false;
5010 }
5011
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005012 private void handleNetworkAgentDisconnected(Message msg) {
5013 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07005014 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005015 }
5016
Chalard Jeand9fffc32018-05-11 20:19:20 +09005017 // Destroys a network, remove references to it from the internal state managed by
5018 // ConnectivityService, free its interfaces and clean up.
5019 // Must be called on the Handler thread.
5020 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005021 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07005022
5023 if (!mNetworkAgentInfos.contains(nai)) return;
5024
Chalard Jeand9fffc32018-05-11 20:19:20 +09005025 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09005026 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005027 }
lucaslinb25c9a62019-02-12 15:30:13 +08005028 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005029 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005030 // A network agent has disconnected.
5031 // TODO - if we move the logic to the network agent (have them disconnect
5032 // because they lost all their requests or because their score isn't good)
5033 // then they would disconnect organically, report their new state and then
5034 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08005035 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005036 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5037 null, null);
5038 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005039 final boolean wasDefault = isDefaultNetwork(nai);
5040 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005041 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005042 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005043 if (mTrackMultiNetworkActivities) {
5044 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5045 // the network becomes no longer the default network.
5046 mNetworkActivityTracker.removeDataActivityTracking(nai);
5047 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005048 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005049 // If this was a local network forwarded to some upstream, or if some local network was
5050 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005051 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005052 // If this is a local network with an upstream selector, remove the associated network
5053 // request.
5054 if (nai.isLocalNetwork()) {
5055 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5056 if (null != selector) {
5057 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5058 }
5059 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005060 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5061 // by other networks that are already connected. Perhaps that can be done by
5062 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5063 // of rematchAllNetworksAndRequests
5064 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005065 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005066
5067 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005068 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5069 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005070 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005071 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005072 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005073 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005074 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005075 synchronized (mNetworkForNetId) {
5076 // Remove the NetworkAgent, but don't mark the netId as
5077 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005078 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005079 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005080 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005081 // Update allowed network lists in netd. This should be called after removing nai
5082 // from mNetworkAgentInfos.
5083 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005084 // Remove all previously satisfied requests.
5085 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005086 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005087 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005088 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005089 if (currentNetwork != null
5090 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005091 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005092 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5093 // rematch not to keep disconnected agents instead of setting it here ; this
5094 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005095 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005096 for (final NetworkOfferInfo noi : mNetworkOffers) {
5097 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005098 }
James Mattise3ef1912020-12-20 11:09:58 -08005099
Chalard Jean5b409c72021-02-04 13:12:59 +09005100 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005101 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005102 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005103 ensureNetworkTransitionWakelock(nai.toShortString());
5104 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005105 }
5106 }
junyulai2b6f0c22021-02-03 20:15:30 +08005107 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005108 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005109 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005110 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005111 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005112 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005113 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005114
Aaron Huang9fe47be2021-06-08 13:11:45 +08005115 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5116 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5117 // not called by the rematch in this case. This is because the code above unset
5118 // this network from the default request's satisfier, and that is what the rematch
5119 // is using as its source data to know what the old satisfier was. So as far as the
5120 // rematch above is concerned, the old default network was null.
5121 // Therefore if there is no new default, the default network was null and is still
5122 // null, thus there was no change so makeDefault() is not called. So if the old
5123 // network had a proxy and there is no new default, the proxy tracker should be told
5124 // that there is no longer a default proxy.
5125 // Strictly speaking this is not essential because having a proxy setting when
5126 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5127 mProxyTracker.setDefaultProxy(null);
5128 }
5129
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005130 // Immediate teardown.
5131 if (nai.teardownDelayMs == 0) {
5132 destroyNetwork(nai);
5133 return;
5134 }
5135
5136 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005137 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305138 try {
5139 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5140 } catch (RemoteException e) {
5141 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5142 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005143 }
5144 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5145 }
5146
5147 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005148 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005149 // Tell netd to clean up the configuration for this network
5150 // (routing rules, DNS, etc).
5151 // This may be slow as it requires a lot of netd shelling out to ip and
5152 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005153 // after we've rematched networks with requests (which might change the default
5154 // network or service a new request from an app), so network traffic isn't interrupted
5155 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005156 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005157 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005158 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005159 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5160 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5161 // false if the network was never created.
5162 // TODO: delete when S is no longer supported.
5163 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005164 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005165 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005166 }
5167
Chalard Jean1e4c2182023-10-06 18:45:53 +09005168 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005169 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005170 // Step 1 : maybe this network was the upstream for one or more local networks.
5171 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5172 if (!local.isLocalNetwork()) continue;
5173 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5174 if (null == selector) continue;
5175 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5176 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5177 // called after removing all associated NRIs from mNetworkRequests.
5178 if (null == nri) continue;
5179 final NetworkAgentInfo satisfier = nri.getSatisfier();
5180 if (disconnecting != satisfier) continue;
5181 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005182 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5183 // correctly contains null as an upstream.
5184 if (sendCallbacks) {
5185 nri.setSatisfier(null, null);
5186 notifyNetworkCallbacks(local,
5187 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5188 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005189 }
5190
5191 // Step 2 : maybe this is a local network that had an upstream.
5192 if (!disconnecting.isLocalNetwork()) return;
5193 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5194 if (null == selector) return;
5195 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5196 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5197 // is called after removing all associated NRIs from mNetworkRequests.
5198 if (null == nri) return;
5199 final NetworkAgentInfo satisfier = nri.getSatisfier();
5200 if (null == satisfier) return;
5201 removeLocalNetworkUpstream(disconnecting, satisfier);
5202 }
5203
5204 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5205 @NonNull final NetworkAgentInfo upstream) {
5206 try {
Yang Sun29037f62023-12-04 10:31:58 +08005207 final String localNetworkInterfaceName = localAgent.linkProperties.getInterfaceName();
5208 final String upstreamNetworkInterfaceName = upstream.linkProperties.getInterfaceName();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005209 mRoutingCoordinatorService.removeInterfaceForward(
Yang Sun29037f62023-12-04 10:31:58 +08005210 localNetworkInterfaceName,
5211 upstreamNetworkInterfaceName);
5212 disableMulticastRouting(localNetworkInterfaceName, upstreamNetworkInterfaceName);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005213 } catch (RemoteException e) {
5214 loge("Couldn't remove interface forward for "
5215 + localAgent.linkProperties.getInterfaceName() + " to "
5216 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5217 }
5218 }
5219
Ken Chen6df7a902021-04-09 15:08:42 +08005220 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005221 try {
5222 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005223 final NativeNetworkConfig config;
5224 if (nai.isVPN()) {
5225 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005226 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005227 return false;
5228 }
5229 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5230 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005231 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005232 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005233 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005234 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005235 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5236 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005237 getNetworkPermission(nai.networkCapabilities),
5238 false /* secure */,
5239 VpnManager.TYPE_VPN_NONE,
5240 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005241 }
Ken Chen6df7a902021-04-09 15:08:42 +08005242 mNetd.networkCreate(config);
5243 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005244 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5245 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005246 return true;
5247 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005248 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005249 return false;
5250 }
5251 }
5252
Ken Chen6df7a902021-04-09 15:08:42 +08005253 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005254 if (mDscpPolicyTracker != null) {
5255 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5256 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005257 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005258 // the interface is going to go away. Don't send the callbacks however ; if the network
5259 // was is being disconnected the callbacks have already been sent, and if it is being
5260 // destroyed pending replacement they will be sent when it is disconnected.
5261 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005262 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005263 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005264 } catch (RemoteException | ServiceSpecificException e) {
5265 loge("Exception destroying network(networkDestroy): " + e);
5266 }
5267 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005268 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005269 } catch (RemoteException | ServiceSpecificException e) {
5270 loge("Exception destroying network: " + e);
5271 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005272 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5273 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5274 // gets created, could add data to DnsManager data structures that will never get deleted.
5275 mDnsManager.removeNetwork(nai.network);
5276
5277 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005278 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005279 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5280 }
5281
Chalard Jean254bd162022-08-25 13:04:51 +09005282 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005283 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005284 }
5285
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005286 // If this method proves to be too slow then we can maintain a separate
5287 // pendingIntent => NetworkRequestInfo map.
5288 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5289 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005290 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5291 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5292 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005293 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005294 return entry.getValue();
5295 }
5296 }
5297 return null;
5298 }
5299
Chalard Jean524f0b12021-10-25 21:11:56 +09005300 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005301 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005302 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5303 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5304 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5305 // bug is fixed.
5306 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005307 throw new IllegalStateException("This NRI is already registered. New : " + nri
5308 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005309 }
5310 }
5311 }
5312 }
5313
Chalard Jeanac9ace02022-01-26 16:54:05 +09005314 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5315 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005316 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005317 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005318 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005319 }
5320 return false;
5321 }
5322
James Mattisf7027322020-12-13 16:28:14 -08005323 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005324 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005325 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5326 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5327 final NetworkRequestInfo existingRequest =
5328 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005329 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005330 if (DBG) {
5331 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5332 + nri.mRequests.get(0) + " because their intents matched.");
5333 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005334 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005335 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005336 }
Erik Kline05f2b402015-04-30 12:58:40 +09005337 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005338 }
5339
James Mattisf7027322020-12-13 16:28:14 -08005340 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005341 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005342 }
5343
James Mattis3ce3d3c2021-02-09 18:18:28 -08005344 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005345 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005346 for (final NetworkRequestInfo nri : nris) {
5347 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005348 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005349 for (final NetworkRequest req : nri.mRequests) {
5350 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005351 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005352 if (req.isListen()) {
5353 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5354 if (req.networkCapabilities.hasSignalStrength()
5355 && network.satisfiesImmutableCapabilitiesOf(req)) {
5356 updateSignalStrengthThresholds(network, "REGISTER", req);
5357 }
James Mattisf7027322020-12-13 16:28:14 -08005358 }
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005359 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5360 mNetworkRequestStateStatsMetrics.onNetworkRequestReceived(req);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005361 }
5362 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005363
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005364 // If this NRI has a satisfier already, it is replacing an older request that
5365 // has been removed. Track it.
5366 final NetworkRequest activeRequest = nri.getActiveRequest();
5367 if (null != activeRequest) {
5368 // If there is an active request, then for sure there is a satisfier.
5369 nri.getSatisfier().addRequest(activeRequest);
5370 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005371 }
James Mattisf7027322020-12-13 16:28:14 -08005372
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005373 if (mFlags.noRematchAllRequestsOnRegister()) {
5374 rematchNetworksAndRequests(nris);
5375 } else {
5376 rematchAllNetworksAndRequests();
5377 }
James Mattis45d81842021-01-10 14:24:24 -08005378
Chalard Jean0354d8c2021-01-12 10:58:56 +09005379 // Requests that have not been matched to a network will not have been sent to the
5380 // providers, because the old satisfier and the new satisfier are the same (null in this
5381 // case). Send these requests to the providers.
5382 for (final NetworkRequestInfo nri : nris) {
5383 for (final NetworkOfferInfo noi : mNetworkOffers) {
5384 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005385 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005386 }
5387 }
5388
James Mattisf7027322020-12-13 16:28:14 -08005389 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5390 final int callingUid) {
5391 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005392 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005393 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5394 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5395 handleReleaseNetworkRequest(
5396 nri.mRequests.get(0),
5397 callingUid,
5398 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005399 }
5400 }
5401
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005402 // Determines whether the network is the best (or could become the best, if it validated), for
5403 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5404 // on the value of reason:
5405 //
5406 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5407 // then it should be torn down.
5408 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5409 // then it should be lingered.
5410 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005411 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005412
Chalard Jean254bd162022-08-25 13:04:51 +09005413 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005414 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5415 return false;
5416 }
5417
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005418 final int numRequests;
5419 switch (reason) {
5420 case TEARDOWN:
5421 numRequests = nai.numRequestNetworkRequests();
5422 break;
5423 case LINGER:
5424 numRequests = nai.numForegroundNetworkRequests();
5425 break;
5426 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005427 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005428 return true;
5429 }
5430
Chalard Jean947acd42021-03-08 22:29:27 +09005431 if (numRequests > 0) return false;
5432
Paul Jensende49eb12015-06-25 15:30:08 -04005433 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005434 if (reason == UnneededFor.LINGER
5435 && !nri.isMultilayerRequest()
5436 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005437 // Background requests don't affect lingering.
5438 continue;
5439 }
5440
James Mattis3d229892020-11-16 16:46:28 -08005441 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005442 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005443 }
5444 }
Paul Jensende49eb12015-06-25 15:30:08 -04005445 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005446 }
5447
James Mattis3d229892020-11-16 16:46:28 -08005448 private boolean isNetworkPotentialSatisfier(
5449 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005450 // While destroyed network sometimes satisfy requests (including occasionally newly
5451 // satisfying requests), *potential* satisfiers are networks that might beat a current
5452 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5453 // because it's never a good idea to keep a destroyed network in case it validates.
5454 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5455 // candidate after it's been replaced by another unvalidated network.
5456 if (candidate.isDestroyed()) return false;
5457 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005458 // request, return immediately. For multilayer requests, check to see if any of the
5459 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005460 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5461 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005462 return false;
5463 }
5464 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005465 // This multilayer listen request is satisfied therefore no further requests need to be
5466 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005467 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005468 return false;
5469 }
James Mattis3d229892020-11-16 16:46:28 -08005470 // As non-multilayer listen requests have already returned, the below would only happen
5471 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005472 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005473 continue;
5474 }
Chalard Jean80685f42023-10-30 18:31:27 +09005475 // If there is hope for this network might validate and subsequently become the best
5476 // network for that request, then it is needed. Note that this network can't already
5477 // be the best for this request, or it would be the current satisfier, and therefore
5478 // there would be no need to call this method to find out if it is a *potential*
5479 // satisfier ("unneeded", the only caller, only calls this if this network currently
5480 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005481 if (candidate.satisfies(req)) {
5482 // As soon as a network is found that satisfies a request, return. Specifically for
5483 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5484 // is important so as to not evaluate lower priority requests further in
5485 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005486 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5487 ? nri.getSatisfier() : null;
5488 // Note that this catches two important cases:
5489 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5490 // is currently satisfying the request. This is desirable when
5491 // cellular ends up validating but WiFi does not.
5492 // 2. Unvalidated WiFi will not be reaped when validated cellular
5493 // is currently satisfying the request. This is desirable when
5494 // WiFi ends up validating and out scoring cellular.
5495 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005496 }
5497 }
5498
5499 return false;
5500 }
5501
Erik Kline0c04b742016-07-07 16:50:58 +09005502 private NetworkRequestInfo getNriForAppRequest(
5503 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005504 // Looking up the app passed param request in mRequests isn't possible since it may return
5505 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5506 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005507 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5508 // to avoid potential race conditions when validating a package->uid mapping when sending
5509 // the callback on the very low-chance that an application shuts down prior to the callback
5510 // being sent.
5511 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5512 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005513
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005514 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005515 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005516 log(String.format("UID %d attempted to %s for unowned request %s",
5517 callingUid, requestedOperation, nri));
5518 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005519 }
Erik Kline0c04b742016-07-07 16:50:58 +09005520 }
5521
5522 return nri;
5523 }
5524
James Mattisf7027322020-12-13 16:28:14 -08005525 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5526 final String callingMethod) {
5527 if (nri.isMultilayerRequest()) {
5528 throw new IllegalStateException(
5529 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005530 }
5531 }
5532
James Mattisf7027322020-12-13 16:28:14 -08005533 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005534 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005535 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5536 // single NetworkRequest and thus does not apply to multilayer requests.
5537 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5538 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005539 return;
5540 }
James Mattis2516da32021-01-31 17:06:19 -08005541 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005542 return;
5543 }
James Mattisf7027322020-12-13 16:28:14 -08005544 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5545 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005546 }
5547 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005548 callCallbackForRequest(
5549 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005550 }
5551
James Mattisf7027322020-12-13 16:28:14 -08005552 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5553 final int callingUid,
5554 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005555 final NetworkRequestInfo nri =
5556 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5557 if (nri == null) {
5558 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005559 }
James Mattisf7027322020-12-13 16:28:14 -08005560 if (VDBG || (DBG && request.isRequest())) {
5561 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005562 }
5563 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005564 if (callOnUnavailable) {
5565 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5566 }
Erik Kline155a59a2015-11-25 12:49:38 +09005567 }
Erik Kline0c04b742016-07-07 16:50:58 +09005568
James Mattisa076c532020-12-02 14:12:41 -08005569 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005570 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005571 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005572 if (null == mNetworkRequests.remove(req)) {
5573 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5574 continue;
5575 }
James Mattisa076c532020-12-02 14:12:41 -08005576 if (req.isListen()) {
5577 removeListenRequestFromNetworks(req);
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005578 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5579 mNetworkRequestStateStatsMetrics.onNetworkRequestRemoved(req);
James Mattisa076c532020-12-02 14:12:41 -08005580 }
5581 }
James Mattis8f036802021-06-20 16:26:01 -07005582 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005583 if (mDefaultNetworkRequests.remove(nri)) {
5584 // If this request was one of the defaults, then the UID rules need to be updated
5585 // WARNING : if the app(s) for which this network request is the default are doing
5586 // traffic, this will kill their connected sockets, even if an equivalent request
5587 // is going to be reinstated right away ; unconnected traffic will go on the default
5588 // until the new default is set, which will happen very soon.
5589 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5590 // remove ranges for those requests that won't have a replacement
5591 final NetworkAgentInfo satisfier = nri.getSatisfier();
5592 if (null != satisfier) {
5593 try {
paulhu0e79d952021-06-09 16:11:35 +08005594 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5595 satisfier.network.getNetId(),
5596 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005597 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005598 } catch (RemoteException e) {
5599 loge("Exception setting network preference default network", e);
5600 }
5601 }
5602 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005603
Junyu Lai00d92df2022-07-05 11:01:52 +08005604 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005605 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005606 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005607
5608 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005609 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005610 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005611 }
5612 }
5613
Chalard Jean0354d8c2021-01-12 10:58:56 +09005614 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5615 // needed for this offer.
5616 for (final NetworkOfferInfo noi : mNetworkOffers) {
5617 for (final NetworkRequest req : nri.mRequests) {
5618 if (req.isRequest() && noi.offer.neededFor(req)) {
5619 noi.offer.onNetworkUnneeded(req);
5620 }
5621 }
5622 }
James Mattisa076c532020-12-02 14:12:41 -08005623 }
5624
James Mattis3ce3d3c2021-02-09 18:18:28 -08005625 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5626 for (final NetworkRequestInfo nri : nris) {
5627 if (mDefaultRequest == nri) {
5628 // Make sure we never remove the default request.
5629 continue;
5630 }
5631 handleRemoveNetworkRequest(nri);
5632 }
5633 }
5634
James Mattisa076c532020-12-02 14:12:41 -08005635 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5636 // listens don't have a singular affected Network. Check all networks to see
5637 // if this listen request applies and remove it.
5638 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5639 nai.removeRequest(req.requestId);
5640 if (req.networkCapabilities.hasSignalStrength()
5641 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5642 updateSignalStrengthThresholds(nai, "RELEASE", req);
5643 }
5644 }
5645 }
5646
5647 /**
5648 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5649 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5650 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5651 */
5652 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5653 boolean wasKept = false;
5654 final NetworkAgentInfo nai = nri.getSatisfier();
5655 if (nai != null) {
5656 final int requestLegacyType = nri.getActiveRequest().legacyType;
5657 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5658 nai.removeRequest(nri.getActiveRequest().requestId);
5659 if (VDBG || DDBG) {
5660 log(" Removing from current network " + nai.toShortString()
5661 + ", leaving " + nai.numNetworkRequests() + " requests.");
5662 }
5663 // If there are still lingered requests on this network, don't tear it down,
5664 // but resume lingering instead.
5665 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005666 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005667 notifyNetworkLosing(nai, now);
5668 }
5669 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5670 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5671 teardownUnneededNetwork(nai);
5672 } else {
5673 wasKept = true;
5674 }
James Mattisa076c532020-12-02 14:12:41 -08005675 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5676 // Went from foreground to background.
5677 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005678 }
5679
Erik Kline0c04b742016-07-07 16:50:58 +09005680 // Maintain the illusion. When this request arrived, we might have pretended
5681 // that a network connected to serve it, even though the network was already
5682 // connected. Now that this request has gone away, we might have to pretend
5683 // that the network disconnected. LegacyTypeTracker will generate that
5684 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005685 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005686 boolean doRemove = true;
5687 if (wasKept) {
5688 // check if any of the remaining requests for this network are for the
5689 // same legacy type - if so, don't remove the nai
5690 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5691 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005692 if (otherRequest.legacyType == requestLegacyType
5693 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005694 if (DBG) log(" still have other legacy request - leaving");
5695 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005696 }
5697 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005698 }
5699
Erik Kline0c04b742016-07-07 16:50:58 +09005700 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005701 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005702 }
5703 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005704 }
5705 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005706
Junyu Lai00d92df2022-07-05 11:01:52 +08005707 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai71b51532024-02-01 10:39:01 +08005708 return hasAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005709 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5710 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5711 }
5712
Lorenzo Colittid6459092016-07-04 12:55:44 +09005713 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005714 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005715 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005716 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005717 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005718 }
5719
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005720 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005721 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5722 enforceNetworkStackSettingsOrSetup();
5723 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5724 encodeBool(accept), encodeBool(always), network));
5725 }
5726
5727 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005728 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005729 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005730 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5731 }
5732
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005733 @Override
5734 public void setTestAllowBadWifiUntil(long timeMs) {
5735 enforceSettingsPermission();
5736 if (!Build.isDebuggable()) {
5737 throw new IllegalStateException("Does not support in non-debuggable build");
5738 }
5739
5740 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5741 throw new IllegalArgumentException("It should not exceed "
5742 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5743 }
5744
5745 mHandler.sendMessage(
5746 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5747 }
5748
chiachangwange0192a72023-02-06 13:25:01 +00005749 @Override
5750 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5751 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005752
5753 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5754 throw new IllegalArgumentException("Argument should not exceed "
5755 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5756 }
5757
5758 mHandler.sendMessage(
5759 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5760 }
5761
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005762 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5763 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5764 " accept=" + accept + " always=" + always);
5765
5766 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5767 if (nai == null) {
5768 // Nothing to do.
5769 return;
5770 }
5771
Chalard Jean254bd162022-08-25 13:04:51 +09005772 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005773 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005774 return;
5775 }
5776
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005777 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005778 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005779 }
5780
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005781 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5782 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005783 // If network becomes partial connectivity and user already accepted to use this
5784 // network, we should respect the user's option and don't need to popup the
5785 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005786 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005787 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005788 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005789 }
5790
5791 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005792 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005793 }
5794
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005795 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005796 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005797 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005798 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005799 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005800 }
5801
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005802 }
5803
lucaslin2240ef62019-03-12 13:08:03 +08005804 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5805 boolean always) {
5806 if (DBG) {
5807 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5808 + " always=" + always);
5809 }
5810
5811 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5812 if (nai == null) {
5813 // Nothing to do.
5814 return;
5815 }
5816
Chalard Jean254bd162022-08-25 13:04:51 +09005817 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005818 // The network validated while the dialog box was up. Take no action.
5819 return;
5820 }
5821
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005822 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5823 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005824 }
5825
5826 // TODO: Use the current design or save the user choice into IpMemoryStore.
5827 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005828 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005829 }
5830
5831 if (!accept) {
5832 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005833 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005834 // Tear down the network.
5835 teardownUnneededNetwork(nai);
5836 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005837 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5838 // result in a partial connectivity result which will be processed by
5839 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005840 //
5841 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5842 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005843 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005844 }
5845 }
5846
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005847 private void handleSetAvoidUnvalidated(Network network) {
5848 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005849 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005850 // Nothing to do. The network either disconnected or revalidated.
5851 return;
5852 }
Chalard Jean254bd162022-08-25 13:04:51 +09005853 if (0L == nai.getAvoidUnvalidated()) {
5854 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005855 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005856 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005857 }
5858 }
5859
Chalard Jean5fb43c72022-09-08 19:03:14 +09005860 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005861 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005862 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005863 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005864 }
5865
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005866 @Override
5867 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005868 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005869 mHandler.post(() -> {
5870 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5871 if (nai == null) return;
5872 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005873 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005874 });
5875 }
5876
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005877 /**
5878 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5879 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005880 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005881 * @param appExtras Bundle to use as intent extras for the captive portal application.
5882 * Must be treated as opaque to avoid preventing the captive portal app to
5883 * update its arguments.
5884 */
5885 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005886 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005887 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5888 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005889
5890 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5891 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005892 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5893 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005894 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5895
lucaslin75ff7022020-12-17 04:14:35 +08005896 final long token = Binder.clearCallingIdentity();
5897 try {
5898 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5899 } finally {
5900 Binder.restoreCallingIdentity(token);
5901 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005902 }
5903
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005904 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5905 private final Network mNetwork;
5906
5907 private CaptivePortalImpl(Network network) {
5908 mNetwork = network;
5909 }
5910
5911 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005912 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005913 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5914 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005915 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5916 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5917 // Since the network will be disconnected, skip notifying NetworkMonitor
5918 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005919 }
5920
Chiachang Wang938bfba2020-01-09 13:50:55 +08005921 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005922 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005923 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005924 }
5925
5926 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005927 public void appRequest(final int request) {
5928 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5929 if (nm == null) return;
5930
5931 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Junyu Lai71b51532024-02-01 10:39:01 +08005932 hasNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005933 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005934 }
5935 }
5936
5937 @Nullable
5938 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5939 // getNetworkAgentInfoForNetwork is thread-safe
5940 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5941 if (nai == null) return null;
5942
5943 // nai.networkMonitor() is thread-safe
5944 return nai.networkMonitor();
5945 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005946 }
5947
Hugo Benichic9048bc2016-09-14 23:23:08 +00005948 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005949 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005950 }
5951
Chalard Jean020b93a2022-09-01 13:20:14 +09005952 private boolean activelyPreferBadWifi() {
5953 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5954 }
5955
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005956 /**
5957 * Return whether the device should maintain continuous, working connectivity by switching away
5958 * from WiFi networks having no connectivity.
5959 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5960 */
5961 public boolean shouldAvoidBadWifi() {
Junyu Lai71b51532024-02-01 10:39:01 +08005962 if (!hasNetworkStackPermission()) {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005963 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5964 }
5965 return avoidBadWifi();
5966 }
5967
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005968 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005969 ensureRunningOnConnectivityServiceThread();
5970 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005971 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005972 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005973 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005974 if (avoidBadWifi) {
5975 // If the device is now avoiding bad wifi, remove notifications that might have
5976 // been put up when the device didn't.
5977 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5978 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005979 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005980 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5981 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5982 for (final NetworkOfferInfo noi : offersToUpdate) {
5983 updateOfferScore(noi.offer);
5984 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005985 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005986 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005987 }
5988
Erik Kline95ecfee2016-10-02 18:02:14 +09005989 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005990 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005991 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005992 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005993 if (!configRestrict) {
5994 pw.println("Bad Wi-Fi avoidance: unrestricted");
5995 return;
5996 }
5997
5998 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5999 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09006000 pw.println("Config restrict: " + configRestrict);
6001 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006002
Chalard Jeane0fdea32022-09-14 21:44:22 +09006003 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006004 String description;
6005 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09006006 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006007 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006008 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006009 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006010 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006011 description = "avoid";
6012 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09006013 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006014 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09006015 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00006016
6017 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
6018 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09006019 if (null == configValue) {
6020 description = "unset";
6021 } else if (configValue) {
6022 description = "force true";
6023 } else {
6024 description = "force false";
6025 }
6026 pw.println("Actively prefer bad wifi conf: " + description);
6027 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006028 pw.println("Network overrides:");
6029 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09006030 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09006031 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09006032 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006033 }
6034 }
6035 pw.decreaseIndent();
6036 pw.decreaseIndent();
6037 }
6038
paulhu7746e4e2020-06-09 19:07:03 +08006039 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
6040 // unify the method.
6041 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
6042 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
6043 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
6044 return settingsComponent != null
6045 ? settingsComponent.getPackageName() : "com.android.settings";
6046 }
6047
lucaslinb1e8e382019-01-24 15:55:30 +08006048 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006049 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006050 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006051 switch (type) {
6052 case NO_INTERNET:
6053 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006054 // High priority because it is only displayed for explicitly selected networks.
6055 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006056 break;
lucasline117e2e2019-10-22 18:27:33 +08006057 case PRIVATE_DNS_BROKEN:
6058 action = Settings.ACTION_WIRELESS_SETTINGS;
6059 // High priority because we should let user know why there is no internet.
6060 highPriority = true;
6061 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006062 case LOST_INTERNET:
6063 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006064 // High priority because it could help the user avoid unexpected data usage.
6065 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006066 break;
lucaslin2240ef62019-03-12 13:08:03 +08006067 case PARTIAL_CONNECTIVITY:
6068 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006069 // Don't bother the user with a high-priority notification if the network was not
6070 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006071 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006072 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006073 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006074 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006075 return;
6076 }
6077
6078 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006079 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006080 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006081 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006082 // Some OEMs have their own Settings package. Thus, need to get the current using
6083 // Settings package name instead of just use default name "com.android.settings".
6084 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6085 intent.setClassName(settingsPkgName,
6086 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006087 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006088
paulhu2af50222020-10-11 22:52:27 +08006089 PendingIntent pendingIntent = PendingIntent.getActivity(
6090 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006091 0 /* requestCode */,
6092 intent,
paulhu2af50222020-10-11 22:52:27 +08006093 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006094
Serik Beketayevec8ad212020-12-07 22:43:07 -08006095 mNotifier.showNotification(
6096 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006097 }
6098
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006099 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6100 // Don't prompt if the network is validated, and don't prompt on captive portals
6101 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006102 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006103 return false;
6104 }
6105
6106 // If a network has partial connectivity, always prompt unless the user has already accepted
6107 // partial connectivity and selected don't ask again. This ensures that if the device
6108 // automatically connects to a network that has partial Internet access, the user will
6109 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006110 // because we have prompted them.
6111 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006112 return true;
6113 }
6114
6115 // If a network has no Internet access, only prompt if the network was explicitly selected
6116 // and if the user has not already told us to use the network regardless of whether it
6117 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006118 if (nai.networkAgentConfig.explicitlySelected
6119 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006120 return true;
6121 }
6122
6123 return false;
6124 }
6125
Chalard Jean5fb43c72022-09-08 19:03:14 +09006126 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6127 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006128
Chalard Jean5fb43c72022-09-08 19:03:14 +09006129 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6130 if (null == nai) return;
6131
6132 if (nai.setEvaluated()) {
6133 // If setEvaluated() returned true, the network never had any form of connectivity.
6134 // This may have an impact on request matching if bad WiFi avoidance is off and the
6135 // network was found not to have Internet access.
6136 nai.updateScoreForNetworkAgentUpdate();
6137 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006138
6139 // Also, if this is WiFi and it should be preferred actively, now is the time to
6140 // prompt the user that they walked past and connected to a bad WiFi.
6141 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6142 && !avoidBadWifi()
6143 && activelyPreferBadWifi()) {
6144 // The notification will be removed if the network validates or disconnects.
6145 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6146 return;
6147 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006148 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006149
Chalard Jean5fb43c72022-09-08 19:03:14 +09006150 if (!shouldPromptUnvalidated(nai)) return;
6151
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006152 // Stop automatically reconnecting to this network in the future. Automatically connecting
6153 // to a network that provides no or limited connectivity is not useful, because the user
6154 // cannot use that network except through the notification shown by this method, and the
6155 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006156 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006157
Chalard Jean254bd162022-08-25 13:04:51 +09006158 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006159 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006160 } else {
6161 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6162 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006163 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006164
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006165 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6166 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006167 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006168
lucaslin2240ef62019-03-12 13:08:03 +08006169 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6170 return;
6171 }
6172
6173 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006174 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006175 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006176 }
6177
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006178 @Override
6179 public int getMultipathPreference(Network network) {
6180 enforceAccessPermission();
6181
6182 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006183 if (nai != null && nai.networkCapabilities
6184 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006185 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6186 }
6187
Aaron Huang9a57acf2020-12-08 10:03:29 +08006188 final NetworkPolicyManager netPolicyManager =
6189 mContext.getSystemService(NetworkPolicyManager.class);
6190
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006191 final long token = Binder.clearCallingIdentity();
6192 final int networkPreference;
6193 try {
6194 networkPreference = netPolicyManager.getMultipathPreference(network);
6195 } finally {
6196 Binder.restoreCallingIdentity(token);
6197 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006198 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006199 return networkPreference;
6200 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006201 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6202 }
6203
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006204 @Override
6205 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006206 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006207 }
6208
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006209 private class InternalHandler extends Handler {
6210 public InternalHandler(Looper looper) {
6211 super(looper);
6212 }
6213
6214 @Override
6215 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006216 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006217 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006218 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006219 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006220 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006221 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006222 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006223 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006224 break;
6225 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006226 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006227 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006228 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006229 break;
6230 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006231 case EVENT_REGISTER_NETWORK_PROVIDER: {
6232 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006233 break;
6234 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006235 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6236 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006237 break;
6238 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006239 case EVENT_REGISTER_NETWORK_OFFER: {
6240 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6241 break;
6242 }
6243 case EVENT_UNREGISTER_NETWORK_OFFER: {
6244 final NetworkOfferInfo offer =
6245 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6246 if (null != offer) {
6247 handleUnregisterNetworkOffer(offer);
6248 }
6249 break;
6250 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006251 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006252 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6253 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6254 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006255 break;
6256 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006257 case EVENT_REGISTER_NETWORK_REQUEST:
6258 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006259 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006260 break;
6261 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006262 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6263 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006264 handleRegisterNetworkRequestWithIntent(msg);
6265 break;
6266 }
Erik Kline155a59a2015-11-25 12:49:38 +09006267 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6268 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6269 handleTimedOutNetworkRequest(nri);
6270 break;
6271 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006272 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6273 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6274 break;
6275 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006276 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006277 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6278 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006279 break;
6280 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006281 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006282 Network network = (Network) msg.obj;
6283 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006284 break;
6285 }
lucaslin2240ef62019-03-12 13:08:03 +08006286 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6287 Network network = (Network) msg.obj;
6288 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6289 toBool(msg.arg2));
6290 break;
6291 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006292 case EVENT_SET_AVOID_UNVALIDATED: {
6293 handleSetAvoidUnvalidated((Network) msg.obj);
6294 break;
6295 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006296 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6297 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006298 break;
6299 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006300 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6301 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006302 break;
6303 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006304 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6305 // handler thread.
6306 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006307 mKeepaliveTracker.handleStartKeepalive(msg);
6308 break;
6309 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006310 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006311 final AutomaticOnOffKeepalive ki =
6312 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6313 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006314
chiachangwang676c84e2023-02-14 09:22:05 +00006315 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006316 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006317 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006318 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006319 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6320 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006321 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6322 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006323 }
6324 }
6325
6326 // If the network no longer exists, then the keepalive should have been
6327 // cleaned up already. There is no point trying to resume keepalives.
6328 if (!networkFound) return;
6329
chiachangwang676c84e2023-02-14 09:22:05 +00006330 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006331 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wangac2e8f32024-01-18 12:55:11 +00006332 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006333 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006334 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006335 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006336 }
6337 break;
6338 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006339 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006340 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006341 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6342 (IBinder) msg.obj);
6343 if (ki == null) {
6344 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006345 return;
6346 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006347 final int reason = msg.arg2;
6348 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006349 break;
6350 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006351 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6352 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6353 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006354 break;
6355 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006356 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6357 handlePrivateDnsSettingsChanged();
6358 break;
dalyk1720e542018-03-05 12:42:22 -05006359 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6360 handlePrivateDnsValidationUpdate(
6361 (PrivateDnsValidationUpdate) msg.obj);
6362 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006363 case EVENT_UID_BLOCKED_REASON_CHANGED:
6364 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006365 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006366 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6367 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6368 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006369 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006370 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6371 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006372 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006373 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006374 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006375 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006376 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6377 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006378 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006379 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006380 }
lucaslin1193a5d2021-01-21 02:04:15 +08006381 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006382 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006383 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006384 break;
paulhu51f77dc2021-06-07 02:34:20 +00006385 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6386 handleMobileDataPreferredUidsChanged();
6387 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006388 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6389 final long timeMs = ((Long) msg.obj).longValue();
6390 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6391 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006392 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6393 handleIngressRateLimitChanged();
6394 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006395 case EVENT_USER_DOES_NOT_WANT:
6396 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6397 if (nai == null) break;
6398 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006399 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006400 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006401 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6402 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6403 break;
chiachangwange0192a72023-02-06 13:25:01 +00006404 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6405 final long time = ((Long) msg.obj).longValue();
6406 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6407 break;
6408 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006409 case EVENT_UID_FROZEN_STATE_CHANGED:
6410 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6411 handleFrozenUids(args.mUids, args.mFrozenStates);
6412 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006413 }
6414 }
6415 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006416
Lorenzo Colittid6459092016-07-04 12:55:44 +09006417 @Override
markchien5776f962019-12-16 20:15:20 +08006418 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006419 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006420 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006421 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6422 Context.TETHERING_SERVICE);
6423 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006424 }
6425
Lorenzo Colittid6459092016-07-04 12:55:44 +09006426 @Override
markchien5776f962019-12-16 20:15:20 +08006427 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006428 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006429 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006430 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6431 Context.TETHERING_SERVICE);
6432 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006433 }
6434
Lorenzo Colittid6459092016-07-04 12:55:44 +09006435 @Override
markchien5776f962019-12-16 20:15:20 +08006436 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006437 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006438 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006439 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6440 Context.TETHERING_SERVICE);
6441 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006442 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006443
markchien5776f962019-12-16 20:15:20 +08006444
Lorenzo Colittid6459092016-07-04 12:55:44 +09006445 @Override
markchien5776f962019-12-16 20:15:20 +08006446 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006447 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006448 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006449 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6450 Context.TETHERING_SERVICE);
6451
6452 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006453 }
6454
Lorenzo Colittid6459092016-07-04 12:55:44 +09006455 @Override
markchien5776f962019-12-16 20:15:20 +08006456 @Deprecated
6457 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006458 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006459 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6460 Context.TETHERING_SERVICE);
6461
6462 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006463 }
6464
Udam Saini8f7d6a72017-06-07 12:06:28 -07006465 @Override
markchien5776f962019-12-16 20:15:20 +08006466 @Deprecated
6467 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006468 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006469 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6470 Context.TETHERING_SERVICE);
6471 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006472 }
6473
Robert Greenwalte0b00512014-07-02 09:59:16 -07006474 // Called when we lose the default network and have no replacement yet.
6475 // This will automatically be cleared after X seconds or a new default network
6476 // becomes CONNECTED, whichever happens first. The timer is started by the
6477 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006478 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006479 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006480 if (mNetTransitionWakeLock.isHeld()) {
6481 return;
6482 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006483 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006484 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6485 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006486 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006487 mWakelockLogs.log("ACQUIRE for " + forWhom);
6488 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006489 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006490 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006491 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006492 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006493
Hugo Benichi471b62a2017-03-30 23:18:10 +09006494 // Called when we gain a new default network to release the network transition wakelock in a
6495 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6496 // message is cancelled.
6497 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006498 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006499 if (!mNetTransitionWakeLock.isHeld()) {
6500 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006501 }
6502 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006503 // Cancel self timeout on wakelock hold.
6504 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6505 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6506 mHandler.sendMessageDelayed(msg, 1000);
6507 }
6508
6509 // Called when either message of ensureNetworkTransitionWakelock or
6510 // scheduleReleaseNetworkTransitionWakelock is processed.
6511 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6512 String event = eventName(eventId);
6513 synchronized (this) {
6514 if (!mNetTransitionWakeLock.isHeld()) {
6515 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006516 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006517 return;
6518 }
6519 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006520 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6521 mTotalWakelockDurationMs += lockDuration;
6522 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6523 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006524 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006525 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006526 }
6527
Robert Greenwalt986c7412010-09-08 15:24:47 -07006528 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006529 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006530 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006531 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006532 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006533 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006534 }
6535
Lorenzo Colittid6459092016-07-04 12:55:44 +09006536 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006537 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006538 enforceAccessPermission();
6539 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006540 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006541 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006542
6543 final NetworkAgentInfo nai;
6544 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006545 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006546 } else {
6547 nai = getNetworkAgentInfoForNetwork(network);
6548 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006549
6550 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006551 mHandler.obtainMessage(
6552 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006553 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006554
Hugo Benichid6b510a2017-04-06 17:22:18 +09006555 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006556 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006557 if (nai == null
6558 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006559 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006560 return;
6561 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006562 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006563 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006564 mConnectivityDiagnosticsHandler.sendMessage(
6565 mConnectivityDiagnosticsHandler.obtainMessage(
6566 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6567 new ReportedNetworkConnectivityInfo(
6568 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006569 return;
6570 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006571 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006572 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006573 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006574 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006575 // Validating a network that has not yet connected could result in a call to
6576 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006577 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006578 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006579 }
paulhu7aeba372020-12-30 00:42:19 +08006580 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6581 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006582 return;
6583 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006584
6585 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6586 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6587 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6588 // completed.
6589 mConnectivityDiagnosticsHandler.sendMessage(
6590 mConnectivityDiagnosticsHandler.obtainMessage(
6591 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6592 new ReportedNetworkConnectivityInfo(
6593 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006594 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006595 }
6596
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006597 // TODO: call into netd.
6598 private boolean queryUserAccess(int uid, Network network) {
6599 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6600 if (nai == null) return false;
6601
6602 // Any UID can use its default network.
6603 if (nai == getDefaultNetworkForUid(uid)) return true;
6604
6605 // Privileged apps can use any network.
6606 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6607 return true;
6608 }
6609
6610 // An unprivileged UID can use a VPN iff the VPN applies to it.
6611 if (nai.isVPN()) {
6612 return nai.networkCapabilities.appliesToUid(uid);
6613 }
6614
6615 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6616 // sockets, i.e., if it is the owner.
6617 final NetworkAgentInfo vpn = getVpnForUid(uid);
6618 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6619 && uid != vpn.networkCapabilities.getOwnerUid()) {
6620 return false;
6621 }
6622
6623 // The UID's permission must be at least sufficient for the network. Since the restricted
6624 // permission was already checked above, that just leaves background networks.
6625 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6626 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6627 }
6628
6629 // Unrestricted network. Anyone gets to use it.
6630 return true;
6631 }
6632
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006633 /**
6634 * Returns information about the proxy a certain network is using. If given a null network, it
6635 * it will return the proxy for the bound network for the caller app or the default proxy if
6636 * none.
6637 *
6638 * @param network the network we want to get the proxy information for.
6639 * @return Proxy information if a network has a proxy configured, or otherwise null.
6640 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006641 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006642 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006643 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006644 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006645 if (network == null) {
6646 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006647 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006648 true);
6649 if (activeNetwork == null) {
6650 return null;
6651 }
6652 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006653 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006654 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6655 // caller may not have.
6656 return getLinkPropertiesProxyInfo(network);
6657 }
6658 // No proxy info available if the calling UID does not have network access.
6659 return null;
6660 }
6661
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006662
6663 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006664 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6665 if (nai == null) return null;
6666 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006667 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6668 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006669 }
6670 }
6671
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006672 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006673 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006674 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006675 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006676 }
6677
Chalard Jean777e2e52018-06-07 18:02:37 +09006678 @Override
6679 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006680 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006681 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006682 }
6683
Aaron Huang9fe47be2021-06-08 13:11:45 +08006684 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006685 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006686 final NetworkAgentInfo nai = getDefaultNetwork();
6687 // TODO : this method should check that net == nai.network, unfortunately at this point
6688 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6689 // is only ever installed on the default network so in practice this is okay.
6690 if (null == nai) return;
6691 // PAC proxies only work on the default network. Therefore, only the default network
6692 // should have its link properties fixed up for PAC proxies.
6693 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6694 if (nai.everConnected()) {
6695 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6696 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006697 }
6698
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006699 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6700 // when any network changes proxy.
6701 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6702 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006703 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6704 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006705 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6706
Chalard Jean7d97afc2018-06-07 17:41:29 +09006707 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006708 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006709 }
6710 }
6711
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006712 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006713 final private HashMap<Uri, Integer> mUriEventMap;
6714 final private Context mContext;
6715 final private Handler mHandler;
6716
6717 SettingsObserver(Context context, Handler handler) {
6718 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006719 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006720 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006721 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006722 }
6723
Erik Kline05f2b402015-04-30 12:58:40 +09006724 void observe(Uri uri, int what) {
6725 mUriEventMap.put(uri, what);
6726 final ContentResolver resolver = mContext.getContentResolver();
6727 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006728 }
6729
6730 @Override
6731 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006732 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006733 }
6734
6735 @Override
6736 public void onChange(boolean selfChange, Uri uri) {
6737 final Integer what = mUriEventMap.get(uri);
6738 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006739 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006740 } else {
6741 loge("No matching event to send for URI=" + uri);
6742 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006743 }
6744 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006745
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006746 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006747 Log.d(TAG, s);
6748 }
6749
6750 private static void logw(String s) {
6751 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006752 }
6753
Daniel Brightf9e945b2020-06-15 16:10:01 -07006754 private static void logwtf(String s) {
6755 Log.wtf(TAG, s);
6756 }
6757
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006758 private static void logwtf(String s, Throwable t) {
6759 Log.wtf(TAG, s, t);
6760 }
6761
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006762 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006763 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006764 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006765
Hugo Benichi39621362017-02-11 17:04:43 +09006766 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006767 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006768 }
6769
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006770 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006771 * Return the information of all ongoing VPNs.
6772 *
6773 * <p>This method is used to update NetworkStatsService.
6774 *
6775 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006776 */
junyulai2050bed2021-01-23 09:46:34 +08006777 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006778 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006779 if (mLockdownEnabled) {
6780 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006781 }
junyulai2050bed2021-01-23 09:46:34 +08006782 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006783 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006784 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006785 if (info != null) {
6786 infoList.add(info);
6787 }
6788 }
junyulai2050bed2021-01-23 09:46:34 +08006789 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006790 }
6791
6792 /**
6793 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006794 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006795 */
junyulai2050bed2021-01-23 09:46:34 +08006796 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006797 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006798 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6799 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006800 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6801 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6802 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006803 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6804 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006805 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006806 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006807 }
6808 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006809
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006810 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006811
6812 List<String> interfaces = new ArrayList<>();
6813 for (Network network : underlyingNetworks) {
6814 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6815 if (underlyingNai == null) continue;
6816 LinkProperties lp = underlyingNai.linkProperties;
6817 for (String iface : lp.getAllInterfaceNames()) {
6818 if (!TextUtils.isEmpty(iface)) {
6819 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006820 }
6821 }
Benedict Wong34857f82019-06-12 17:46:15 +00006822 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006823
6824 if (interfaces.isEmpty()) return null;
6825
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006826 // Must be non-null or NetworkStatsService will crash.
6827 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6828 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006829 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006830 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006831
junyulai2050bed2021-01-23 09:46:34 +08006832 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6833 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006834 }
6835
James Mattisd31bdfa2020-12-23 16:37:26 -08006836 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006837 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6838 Network[] underlyingNetworks) {
6839 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006840 if (underlyingNetworks == null && defaultNetwork != null) {
6841 // null underlying networks means to track the default.
6842 underlyingNetworks = new Network[] { defaultNetwork };
6843 }
6844 return underlyingNetworks;
6845 }
6846
6847 // Returns true iff |network| is an underlying network of |nai|.
6848 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6849 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6850 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006851 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006852 final Network[] underlying = underlyingNetworksOrDefault(
6853 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006854 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006855 }
6856
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006857 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006858 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006859 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006860 * When underlying networks change, such networks may have to update capabilities to reflect
6861 * things like the metered bit, their transports, and so on. The capabilities are calculated
6862 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006863 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006864 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006865 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006866 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006867 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006868 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006869 }
6870 }
6871 }
6872
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006873 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6874 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6875 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6876 // a VPN is not up.
6877 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6878 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6879 for (UidRange range : blockedUidRanges) {
6880 if (range.contains(uid)) return true;
6881 }
6882 return false;
6883 }
6884
6885 @Override
6886 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006887 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006888 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6889 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6890 }
6891
6892 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6893 if (DBG) {
6894 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6895 + Arrays.toString(ranges));
6896 }
6897 // Cannot use a Set since the list of UID ranges might contain duplicates.
6898 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6899 for (int i = 0; i < ranges.length; i++) {
6900 if (requireVpn) {
6901 newVpnBlockedUidRanges.add(ranges[i]);
6902 } else {
6903 newVpnBlockedUidRanges.remove(ranges[i]);
6904 }
6905 }
6906
6907 try {
6908 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6909 } catch (RemoteException | ServiceSpecificException e) {
6910 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6911 + Arrays.toString(ranges) + "): netd command failed: " + e);
6912 }
6913
Chalard Jeandf29a852023-05-29 17:02:43 +09006914 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006915 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6916 }
6917
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006918 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6919 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006920 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6921 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006922 }
6923
6924 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6925 }
6926
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006927 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006928 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006929 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006930 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006931 }
6932
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006933 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6934 return mLockdownEnabled
6935 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6936 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006937 }
6938
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006939 private NetworkAgentInfo getLegacyLockdownNai() {
6940 if (!mLockdownEnabled) {
6941 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006942 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006943 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006944 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6945 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006946
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006947 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006948 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6949 // a local variable. There is no need to make a copy because its contents cannot change.
6950 final Network[] underlying = nai.declaredUnderlyingNetworks;
6951 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006952 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006953 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006954
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006955 // The legacy lockdown VPN always uses the default network.
6956 // If the VPN's underlying network is no longer the current default network, it means that
6957 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006958 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6959 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006960 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006961 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006962 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006963 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006964
6965 return nai;
6966 };
6967
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006968 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6969 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6970 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006971 private DetailedState getLegacyLockdownState(DetailedState origState) {
6972 if (origState != DetailedState.CONNECTED) {
6973 return origState;
6974 }
6975 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6976 ? DetailedState.CONNECTING
6977 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006978 }
6979
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006980 private void filterForLegacyLockdown(NetworkInfo ni) {
6981 if (!mLockdownEnabled || !ni.isConnected()) return;
6982 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6983 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6984 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6985 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6986 // network, this time with a state of CONNECTED.
6987 //
6988 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6989 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6990 // is not too far off the truth, since an always-on VPN, when not connected, is always
6991 // trying to reconnect.
6992 if (getLegacyLockdownNai() == null) {
6993 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6994 }
6995 }
6996
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006997 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006998 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006999 String action) {
paulhu8e96a752019-08-12 16:25:11 +08007000 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09007001 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
7002 return;
7003 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04007004 final long ident = Binder.clearCallingIdentity();
7005 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09007006 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007007 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09007008 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04007009 } finally {
7010 Binder.restoreCallingIdentity(ident);
7011 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07007012 }
Wink Savillecb117d32013-08-29 14:57:08 -07007013
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007014 @Override
7015 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01007016 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007017 final long ident = Binder.clearCallingIdentity();
7018 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007019 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09007020 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007021 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
7022 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08007023 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007024 } finally {
7025 Binder.restoreCallingIdentity(ident);
7026 }
7027 }
7028
James Mattis02220e22021-03-13 19:27:21 -08007029 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08007030 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7031 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7032 }
Chalard Jeane0abd522023-01-23 16:47:43 +09007033 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007034 }
7035
James Mattis02220e22021-03-13 19:27:21 -08007036 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09007037 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007038 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08007039 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
7040 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09007041 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08007042 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7043 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7044 }
junyulaid91e7052020-08-28 13:44:33 +08007045 }
7046
James Mattis02220e22021-03-13 19:27:21 -08007047 private void onPackageChanged(@NonNull final String packageName) {
7048 // This is necessary in case a package is added or removed, but also when it's replaced to
7049 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
7050 // as one in the preferences, then it should follow the same routing as that other package,
7051 // which means updating the rules is never to be needed in this case (whether it joins or
7052 // leaves a UID with a preference).
7053 if (isMappedInOemNetworkPreference(packageName)) {
7054 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7055 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007056
7057 // Invalidates cache entry when the package is updated.
7058 synchronized (mSelfCertifiedCapabilityCache) {
7059 mSelfCertifiedCapabilityCache.remove(packageName);
7060 }
James Mattis02220e22021-03-13 19:27:21 -08007061 }
7062
7063 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007064 @Override
7065 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007066 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007067 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007068 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007069
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007070 // User should be filled for below intents, check the existence.
7071 if (user == null) {
7072 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7073 return;
7074 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007075
Lorenzo Colitticd675292021-02-04 17:32:07 +09007076 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007077 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007078 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007079 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007080 } else {
junyulaid91e7052020-08-28 13:44:33 +08007081 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007082 }
7083 }
7084 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007085
James Mattis02220e22021-03-13 19:27:21 -08007086 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7087 @Override
7088 public void onReceive(Context context, Intent intent) {
7089 ensureRunningOnConnectivityServiceThread();
7090 switch (intent.getAction()) {
7091 case Intent.ACTION_PACKAGE_ADDED:
7092 case Intent.ACTION_PACKAGE_REMOVED:
7093 case Intent.ACTION_PACKAGE_REPLACED:
7094 onPackageChanged(intent.getData().getSchemeSpecificPart());
7095 break;
7096 default:
7097 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7098 }
7099 }
7100 };
7101
Junyu Lai38c75032023-12-04 07:52:19 +00007102 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
7103 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
7104 @Override
7105 public void onReceive(Context context, Intent intent) {
7106 if (mDeps.isAtLeastV()) {
7107 throw new IllegalStateException(
7108 "data saver status should be updated from platform");
7109 }
7110 ensureRunningOnConnectivityServiceThread();
7111 switch (intent.getAction()) {
7112 case ACTION_RESTRICT_BACKGROUND_CHANGED:
7113 // If the uid is present in the deny list, the API will consistently
7114 // return ENABLED. To retrieve the global switch status, the system
7115 // uid is chosen because it will never be included in the deny list.
7116 final int dataSaverForSystemUid =
7117 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
7118 final boolean isDataSaverEnabled = (dataSaverForSystemUid
7119 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
7120 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
7121 break;
7122 default:
7123 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7124 }
7125 }
7126 };
7127
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007128 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007129 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007130
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007131 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007132 public final String name;
7133 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007134 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007135 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007136
lifraf3a3492021-03-10 13:58:14 +08007137 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7138 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007139 this.name = name;
7140 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007141 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007142 mDeathRecipient = deathRecipient;
7143
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007144 if (mDeathRecipient == null) {
7145 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007146 }
7147 }
7148
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007149 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007150 try {
7151 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7152 } catch (RemoteException e) {
7153 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007154 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007155 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007156 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007157
James Mattis4fce5d12020-11-12 15:53:42 -08007158 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7159 for (int i = 0; i < requests.size(); i++) {
7160 ensureNetworkRequestHasType(requests.get(i));
7161 }
7162 }
7163
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007164 private void ensureNetworkRequestHasType(NetworkRequest request) {
7165 if (request.type == NetworkRequest.Type.NONE) {
7166 throw new IllegalArgumentException(
7167 "All NetworkRequests in ConnectivityService must have a type");
7168 }
7169 }
7170
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007171 /**
7172 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007173 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007174 */
James Mattis258ea3c2020-11-15 15:04:40 -08007175 @VisibleForTesting
7176 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007177 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7178 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007179 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007180
James Mattisa076c532020-12-02 14:12:41 -08007181 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7182 void setSatisfier(
7183 @Nullable final NetworkAgentInfo satisfier,
7184 @Nullable final NetworkRequest activeRequest) {
7185 mSatisfier = satisfier;
7186 mActiveRequest = activeRequest;
7187 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007188
James Mattisd31bdfa2020-12-23 16:37:26 -08007189 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007190 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007191 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007192 private NetworkAgentInfo mSatisfier;
7193 NetworkAgentInfo getSatisfier() {
7194 return mSatisfier;
7195 }
7196
7197 // The request in mRequests assigned to a network agent. This is null if none of the
7198 // requests in mRequests can be satisfied. This member has the constraint of only being
7199 // accessible on the handler thread.
7200 @Nullable
7201 private NetworkRequest mActiveRequest;
7202 NetworkRequest getActiveRequest() {
7203 return mActiveRequest;
7204 }
7205
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007206 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007207 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007208 @Nullable
7209 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007210
7211 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007212 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007213 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007214 final int mPid;
7215 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007216 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007217 @Nullable
7218 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007219
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007220 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007221 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007222
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007223 // Effective UID of this request. This is different from mUid when a privileged process
7224 // files a request on behalf of another UID. This UID is used to determine blocked status,
7225 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7226 // maximum limit of registered callbacks per UID.
7227 final int mAsUid;
7228
paulhu48291862021-07-14 14:53:57 +08007229 // Preference order of this request.
7230 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007231
James Mattis3ce3d3c2021-02-09 18:18:28 -08007232 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7233 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7234 // maintained for keying off of. This is only a concern when the original nri
7235 // mNetworkRequests changes which happens currently for apps that register callbacks to
7236 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7237 // that match the per-app default nri that currently tracks the calling app's uid so that
7238 // callbacks are fired at the appropriate time. When the callbacks fire,
7239 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7240 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7241 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7242 @NonNull
7243 private final NetworkRequest mNetworkRequestForCallback;
7244 NetworkRequest getNetworkRequestForCallback() {
7245 return mNetworkRequestForCallback;
7246 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007247
James Mattisd31bdfa2020-12-23 16:37:26 -08007248 /**
7249 * Get the list of UIDs this nri applies to.
7250 */
7251 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007252 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007253 // networkCapabilities.getUids() returns a defensive copy.
7254 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007255 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7256 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007257 }
7258
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007259 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7260 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007261 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007262 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007263 }
7264
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007265 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007266 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007267 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007268 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007269 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007270 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007271 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007272 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007273 mBinder = null;
7274 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007275 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007276 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007277 mPerUidCounter = getRequestCounter(this);
7278 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007279 /**
7280 * Location sensitive data not included in pending intent. Only included in
7281 * {@link NetworkCallback}.
7282 */
7283 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007284 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007285 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007286 }
7287
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007288 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007289 @Nullable final IBinder binder,
7290 @NetworkCallback.Flag int callbackFlags,
7291 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007292 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7293 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007294 }
7295
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007296 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007297 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007298 @Nullable final IBinder binder,
7299 @NetworkCallback.Flag int callbackFlags,
7300 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007301 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007302 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007303 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007304 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007305 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007306 mBinder = binder;
7307 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007308 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007309 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007310 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007311 mPerUidCounter = getRequestCounter(this);
7312 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007313 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007314 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007315 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007316 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007317 }
7318
James Mattis3ce3d3c2021-02-09 18:18:28 -08007319 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7320 @NonNull final List<NetworkRequest> r) {
7321 super();
7322 ensureAllNetworkRequestsHaveType(r);
7323 mRequests = initializeRequests(r);
7324 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007325 final NetworkAgentInfo satisfier = nri.getSatisfier();
7326 if (null != satisfier) {
7327 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7328 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007329 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007330 // As this code creates a new NRI with a new set of requests, figure out which of
7331 // the list of requests should be the active request. It is always the first
7332 // request of the list that can be satisfied by the satisfier since the order of
7333 // requests is a priority order.
7334 // Note even in the presence of a satisfier there may not be an active request,
7335 // when the satisfier is the no-service network.
7336 NetworkRequest activeRequest = null;
7337 for (final NetworkRequest candidate : r) {
7338 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7339 activeRequest = candidate;
7340 break;
7341 }
7342 }
7343 setSatisfier(satisfier, activeRequest);
7344 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007345 mMessenger = nri.mMessenger;
7346 mBinder = nri.mBinder;
7347 mPid = nri.mPid;
7348 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007349 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007350 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007351 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007352 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007353 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007354 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007355 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007356 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007357 }
7358
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007359 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007360 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007361 }
7362
paulhue9913722021-05-26 15:19:20 +08007363 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007364 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007365 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007366 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007367 }
7368
James Mattis2516da32021-01-31 17:06:19 -08007369 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7370 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7371 // false.
7372 boolean isBeingSatisfied() {
7373 return (null != mSatisfier && null != mActiveRequest);
7374 }
7375
James Mattis3d229892020-11-16 16:46:28 -08007376 boolean isMultilayerRequest() {
7377 return mRequests.size() > 1;
7378 }
7379
James Mattis45d81842021-01-10 14:24:24 -08007380 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7381 // Creating a defensive copy to prevent the sender from modifying the list being
7382 // reflected in the return value of this method.
7383 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007384 return Collections.unmodifiableList(tempRequests);
7385 }
7386
James Mattisb1392002021-03-31 13:57:52 -07007387 void linkDeathRecipient() {
7388 if (null != mBinder) {
7389 try {
7390 mBinder.linkToDeath(this, 0);
7391 } catch (RemoteException e) {
7392 binderDied();
7393 }
7394 }
7395 }
7396
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007397 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007398 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007399 try {
7400 mBinder.unlinkToDeath(this, 0);
7401 } catch (NoSuchElementException e) {
7402 // Temporary workaround for b/194394697 pending analysis of additional logs
7403 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7404 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007405 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007406 }
7407
paulhu48291862021-07-14 14:53:57 +08007408 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7409 // Compare two preference orders.
7410 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007411 }
7412
paulhu48291862021-07-14 14:53:57 +08007413 int getPreferenceOrderForNetd() {
7414 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7415 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7416 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007417 }
paulhu48291862021-07-14 14:53:57 +08007418 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007419 }
7420
James Mattis4fce5d12020-11-12 15:53:42 -08007421 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007422 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007423 // As an immutable collection, mRequests cannot change by the time the
7424 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7425 // is acceptable. Use handleReleaseNetworkRequest and not directly
7426 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7427 // the app already unregistered the request.
7428 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7429 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007430 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007431
James Mattis4fce5d12020-11-12 15:53:42 -08007432 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007433 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007434 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7435 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007436 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007437 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007438 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007439 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007440 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007441 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007442 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007443 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007444 }
7445
Junyu Lai00d92df2022-07-05 11:01:52 +08007446 // Keep backward compatibility since the ServiceSpecificException is used by
7447 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7448 public static class RequestInfoPerUidCounter extends PerUidCounter {
7449 RequestInfoPerUidCounter(int maxCountPerUid) {
7450 super(maxCountPerUid);
7451 }
7452
7453 @Override
7454 public synchronized void incrementCountOrThrow(int uid) {
7455 try {
7456 super.incrementCountOrThrow(uid);
7457 } catch (IllegalStateException e) {
7458 throw new ServiceSpecificException(
7459 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7460 "Uid " + uid + " exceeded its allotted requests limit");
7461 }
7462 }
7463
7464 @Override
7465 public synchronized void decrementCountOrThrow(int uid) {
7466 throw new UnsupportedOperationException("Use decrementCount instead.");
7467 }
7468
7469 public synchronized void decrementCount(int uid) {
7470 try {
7471 super.decrementCountOrThrow(uid);
7472 } catch (IllegalStateException e) {
7473 logwtf("Exception when decrement per uid request count: ", e);
7474 }
7475 }
7476 }
7477
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007478 // This checks that the passed capabilities either do not request a
7479 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007480 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007481 int callerPid, int callerUid, String callerPackageName) {
Junyu Lai71b51532024-02-01 10:39:01 +08007482 if (null != nc.getSsid() && !hasSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007483 throw new SecurityException("Insufficient permissions to request a specific SSID");
7484 }
paulhu1a407652019-03-22 16:35:06 +08007485
7486 if (nc.hasSignalStrength()
Junyu Lai71b51532024-02-01 10:39:01 +08007487 && !hasNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
paulhu1a407652019-03-22 16:35:06 +08007488 throw new SecurityException(
7489 "Insufficient permissions to request a specific signal strength");
7490 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007491 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007492
junyulai2217bec2021-04-14 23:33:31 +08007493 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007494 enforceNetworkFactoryPermission();
7495 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007496 }
7497
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007498 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007499 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007500 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007501 // mNetworkRequests may contain the same value multiple times in case of
7502 // multilayer requests. It won't matter in this case because the thresholds
7503 // will then be the same and be deduplicated as they enter the `thresholds` set.
7504 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007505 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7506 for (final NetworkRequest req : nri.mRequests) {
7507 if (req.networkCapabilities.hasSignalStrength()
7508 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7509 thresholds.add(req.networkCapabilities.getSignalStrength());
7510 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007511 }
7512 }
7513 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007514 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007515 }
7516
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007517 private void updateSignalStrengthThresholds(
7518 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007519 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007520
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007521 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007522 String detail;
7523 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7524 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7525 } else {
7526 detail = reason;
7527 }
7528 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007529 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007530 }
7531
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007532 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007533 }
7534
Chalard Jeandd421992021-12-16 23:16:02 +09007535 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007536 if (nc == null) {
7537 return;
7538 }
7539 NetworkSpecifier ns = nc.getNetworkSpecifier();
7540 if (ns == null) {
7541 return;
7542 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007543 if (ns instanceof MatchAllNetworkSpecifier) {
7544 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7545 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007546 }
7547
Chalard Jeandd421992021-12-16 23:16:02 +09007548 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007549 ensureValidNetworkSpecifier(nc);
7550 if (nc.isPrivateDnsBroken()) {
7551 throw new IllegalArgumentException("Can't request broken private DNS");
7552 }
Chalard Jeande665262022-02-25 16:12:12 +09007553 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007554 throw new IllegalArgumentException("Can't request access UIDs");
7555 }
lucasline117e2e2019-10-22 18:27:33 +08007556 }
7557
Chalard Jeandd421992021-12-16 23:16:02 +09007558 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7559 ensureListenableCapabilities(nc);
7560 final String badCapability = nc.describeFirstNonRequestableCapability();
7561 if (badCapability != null) {
7562 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7563 }
7564 }
7565
Chiachang Wang3bc52762021-11-25 14:17:57 +08007566 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7567 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007568 private boolean isTargetSdkAtleast(int version, int callingUid,
7569 @NonNull String callingPackageName) {
7570 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007571 final PackageManager pm =
7572 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007573 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007574 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007575 if (callingVersion < version) return false;
7576 } catch (PackageManager.NameNotFoundException e) { }
7577 return true;
7578 }
7579
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007580 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007581 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007582 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007583 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007584 @Nullable String callingAttributionTag) {
Junyu Lai71b51532024-02-01 10:39:01 +08007585 if (legacyType != TYPE_NONE && !hasNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007586 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7587 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007588 throw new SecurityException("Insufficient permissions to specify legacy type");
7589 }
markchienfac84a22020-03-18 21:16:15 +08007590 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007591 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007592 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007593 // Privileged callers can track the default network of another UID by passing in a UID.
7594 if (asUid != Process.INVALID_UID) {
7595 enforceSettingsPermission();
7596 } else {
7597 asUid = callingUid;
7598 }
junyulaiad010792021-01-11 16:53:38 +08007599 final NetworkRequest.Type reqType;
7600 try {
7601 reqType = NetworkRequest.Type.values()[reqTypeInt];
7602 } catch (ArrayIndexOutOfBoundsException e) {
7603 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7604 }
7605 switch (reqType) {
7606 case TRACK_DEFAULT:
7607 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007608 // is unused and will be replaced by ones appropriate for the UID (usually, the
7609 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007610 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007611 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007612 enforceAccessPermission();
7613 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007614 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007615 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007616 networkCapabilities = new NetworkCapabilities(defaultNc);
7617 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007618 case BACKGROUND_REQUEST:
7619 enforceNetworkStackOrSettingsPermission();
7620 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007621 case REQUEST:
7622 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7623 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007624 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007625 // TODO: this is incorrect. We mark the request as metered or not depending on
7626 // the state of the app when the request is filed, but we never change the
7627 // request if the app changes network state. http://b/29964605
7628 enforceMeteredApnPolicy(networkCapabilities);
7629 break;
junyulai1b1c8742021-03-12 20:05:08 +08007630 case LISTEN_FOR_BEST:
7631 enforceAccessPermission();
7632 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7633 break;
junyulaiad010792021-01-11 16:53:38 +08007634 default:
7635 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007636 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007637 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007638 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007639 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007640
junyulai1b1c8742021-03-12 20:05:08 +08007641 // Enforce FOREGROUND if the caller does not have permission to use background network.
7642 if (reqType == LISTEN_FOR_BEST) {
7643 restrictBackgroundRequestForCaller(networkCapabilities);
7644 }
7645
7646 // Set the UID range for this request to the single UID of the requester, unless the
7647 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007648 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7649 // are no visible methods to set the UIDs, an app could use reflection to try and get
7650 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007651 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007652 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7653 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007654
Etan Cohen85000162017-02-05 10:42:27 -08007655 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007656 throw new IllegalArgumentException("Bad timeout specified");
7657 }
Etan Cohen9786d922015-11-18 10:56:15 -08007658
James Mattis3ce3d3c2021-02-09 18:18:28 -08007659 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007660 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007661 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007662 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007663 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007664 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007665
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007666 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7667 // copied from the default request above. (This is necessary to ensure, for example, that
7668 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7669 // changes don't alter request matching.
7670 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7671 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007672 throw new IllegalStateException(
7673 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007674 + networkCapabilities + " vs. " + defaultNc);
7675 }
7676
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007677 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007678 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007679 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007680 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007681 }
7682 return networkRequest;
7683 }
7684
James Mattis3ce3d3c2021-02-09 18:18:28 -08007685 /**
7686 * Return the nri to be used when registering a network request. Specifically, this is used with
7687 * requests registered to track the default request. If there is currently a per-app default
7688 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7689 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007690 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7691 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007692 * @param nr the network request for the nri.
7693 * @param msgr the messenger for the nri.
7694 * @param binder the binder for the nri.
7695 * @param callingAttributionTag the calling attribution tag for the nri.
7696 * @return the nri to register.
7697 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007698 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007699 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007700 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007701 @Nullable String callingAttributionTag) {
7702 final List<NetworkRequest> requests;
7703 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7704 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007705 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007706 } else {
7707 requests = Collections.singletonList(nr);
7708 }
Roshan Pius951c0032020-12-22 15:10:42 -08007709 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007710 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007711 }
7712
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007713 private boolean shouldCheckCapabilitiesDeclaration(
7714 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7715 @NonNull final String callingPackageName) {
7716 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7717 // Only run the check if the change is enabled.
7718 if (!mDeps.isChangeEnabled(
7719 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7720 callingPackageName, user)) {
7721 return false;
7722 }
7723
7724 return networkCapabilities.hasCapability(
7725 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7726 || networkCapabilities.hasCapability(
7727 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7728 }
7729
7730 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007731 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007732 // This check is added to fix the linter error for "current min is 30", which is not going
7733 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007734 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007735 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7736 return;
7737 }
7738 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007739 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007740 try {
7741 synchronized (mSelfCertifiedCapabilityCache) {
7742 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7743 callerPackageName);
7744 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007745 final PackageManager packageManager =
7746 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
7747 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007748 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7749 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7750 callerPackageName
7751 );
7752 final XmlResourceParser parser = packageManager
7753 .getResourcesForApplication(callerPackageName)
7754 .getXml(networkSliceProperty.getResourceId());
7755 applicationNetworkCapabilities =
7756 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7757 mSelfCertifiedCapabilityCache.put(callerPackageName,
7758 applicationNetworkCapabilities);
7759 }
7760
7761 }
7762 } catch (PackageManager.NameNotFoundException ne) {
7763 throw new SecurityException(
7764 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7765 + " property");
7766 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7767 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007768 } finally {
7769 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007770 }
7771
7772 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7773 networkCapabilities);
7774 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007775 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007776 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007777 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7778 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007779 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
7780 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007781 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007782 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007783 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7784 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7785 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7786 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007787 }
junyulai96bd9fe2022-03-08 17:36:42 +08007788 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007789 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007790 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007791 }
7792 }
7793
fenglu3f357402015-03-20 11:29:56 -07007794 @Override
fenglub00f4882015-04-21 17:12:05 -07007795 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007796 enforceAccessPermission();
7797 NetworkAgentInfo nai = null;
7798 if (network == null) {
7799 return false;
7800 }
7801 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007802 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007803 }
7804 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007805 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007806 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007807 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007808 Integer uidReqs = mBandwidthRequests.get(uid);
7809 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007810 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007811 }
7812 mBandwidthRequests.put(uid, ++uidReqs);
7813 }
fenglu3f357402015-03-20 11:29:56 -07007814 return true;
7815 }
7816 return false;
7817 }
7818
Felipe Leme0a5ae422016-06-20 16:36:29 -07007819 private boolean isSystem(int uid) {
7820 return uid < Process.FIRST_APPLICATION_UID;
7821 }
fenglu3f357402015-03-20 11:29:56 -07007822
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007823 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007824 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007825 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007826 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007827 return;
7828 }
Hugo Benichi39621362017-02-11 17:04:43 +09007829 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7830 // Policy already enforced.
7831 return;
7832 }
paulhuaf50d7d2020-12-24 19:47:34 +08007833 final long ident = Binder.clearCallingIdentity();
7834 try {
7835 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7836 // If UID is restricted, don't allow them to bring up metered APNs.
7837 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7838 }
7839 } finally {
7840 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007841 }
7842 }
7843
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007844 @Override
7845 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007846 PendingIntent operation, @NonNull String callingPackageName,
7847 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007848 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007849 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007850 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007851 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007852 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007853 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007854 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007855 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007856 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007857 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7858 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007859
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007860 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007861 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007862 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7863 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007864 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007865 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7866 nri));
7867 return networkRequest;
7868 }
7869
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007870 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7871 mHandler.sendMessageDelayed(
7872 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007873 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007874 }
7875
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007876 @Override
7877 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007878 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007879 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007880 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007881 }
7882
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007883 // In order to implement the compatibility measure for pre-M apps that call
7884 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7885 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7886 // This ensures it has permission to do so.
7887 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7888 if (nc == null) {
7889 return false;
7890 }
7891 int[] transportTypes = nc.getTransportTypes();
7892 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7893 return false;
7894 }
7895 try {
7896 mContext.enforceCallingOrSelfPermission(
7897 android.Manifest.permission.ACCESS_WIFI_STATE,
7898 "ConnectivityService");
7899 } catch (SecurityException e) {
7900 return false;
7901 }
7902 return true;
7903 }
7904
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007905 @Override
7906 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007907 Messenger messenger, IBinder binder,
7908 @NetworkCallback.Flag int callbackFlags,
7909 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007910 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007911 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7912 enforceAccessPermission();
7913 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007914
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007915 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007916 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007917 Binder.getCallingPid(), callingUid, callingPackageName);
7918 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007919 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7920 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7921 // onLost and onAvailable callbacks when networks move in and out of the background.
7922 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7923 // can't request networks.
7924 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007925 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007926
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007927 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007928 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007929 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007930 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007931 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007932 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007933
7934 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7935 return networkRequest;
7936 }
7937
7938 @Override
7939 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007940 PendingIntent operation, @NonNull String callingPackageName,
7941 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007942 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007943 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007944 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7945 enforceAccessPermission();
7946 }
Chalard Jeandd421992021-12-16 23:16:02 +09007947 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007948 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007949 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007950 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007951 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007952
7953 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007954 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007955 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7956 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007957 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007958
WeiZhang1cc3f172021-06-03 19:02:04 -05007959 mHandler.sendMessage(mHandler.obtainMessage(
7960 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007961 }
7962
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007963 /** Returns the next Network provider ID. */
7964 public final int nextNetworkProviderId() {
7965 return mNextNetworkProviderId.getAndIncrement();
7966 }
7967
Erik Kline0c04b742016-07-07 16:50:58 +09007968 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007969 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007970 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007971 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007972 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007973 }
7974
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007975 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7976 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007977 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7978 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7979 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007980 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007981 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007982 return;
7983 }
7984
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007985 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7986 mNetworkProviderInfos.put(npi.messenger, npi);
7987 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007988 }
7989
7990 @Override
7991 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007992 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007993 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007994 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007995 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007996 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7997 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007998 }
7999
8000 @Override
8001 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008002 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008003 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008004 }
8005
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008006 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09008007 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008008 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
8009 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09008010 Objects.requireNonNull(score);
8011 Objects.requireNonNull(caps);
8012 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008013 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008014 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09008015 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
8016 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008017 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
8018 }
8019
Chalard Jeanbb902a52021-08-18 01:35:19 +09008020 private void updateOfferScore(final NetworkOffer offer) {
8021 final boolean yieldToBadWiFi =
8022 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
8023 final NetworkOffer newOffer = new NetworkOffer(
8024 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
8025 offer.caps, offer.callback, offer.providerId);
8026 if (offer.equals(newOffer)) return;
8027 handleRegisterNetworkOffer(newOffer);
8028 }
8029
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008030 @Override
8031 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08008032 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008033 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
8034 }
8035
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008036 private void handleUnregisterNetworkProvider(Messenger messenger) {
8037 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
8038 if (npi == null) {
8039 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008040 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008041 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008042 // Unregister all the offers from this provider
8043 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
8044 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09008045 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008046 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
8047 toRemove.add(noi);
8048 }
8049 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09008050 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008051 handleUnregisterNetworkOffer(noi);
8052 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008053 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008054 }
8055
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008056 @Override
James Mattisf7027322020-12-13 16:28:14 -08008057 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008058 if (request.hasTransport(TRANSPORT_TEST)) {
8059 enforceNetworkFactoryOrTestNetworksPermission();
8060 } else {
8061 enforceNetworkFactoryPermission();
8062 }
James Mattisf7027322020-12-13 16:28:14 -08008063 final NetworkRequestInfo nri = mNetworkRequests.get(request);
8064 if (nri != null) {
8065 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
8066 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
8067 mHandler.post(() -> handleReleaseNetworkRequest(
8068 nri.mRequests.get(0), mDeps.getCallingUid(), true));
8069 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008070 }
8071
Paul Jensen1f567382015-02-13 14:18:39 -05008072 // NOTE: Accessed on multiple threads, must be synchronized on itself.
8073 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008074 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008075 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008076 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008077 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008078 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008079
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008080 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008081 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008082 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008083
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008084 // UID ranges for users that are currently blocked by VPNs.
8085 // This array is accessed and iterated on multiple threads without holding locks, so its
8086 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8087 // (on the handler thread).
8088 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8089
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008090 // Must only be accessed on the handler thread
8091 @NonNull
8092 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8093
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008094 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008095 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008096
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008097 // Current OEM network preferences. This object must only be written to on the handler thread.
8098 // Since it is immutable and always non-null, other threads may read it if they only care
8099 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008100 @NonNull
8101 private OemNetworkPreferences mOemNetworkPreferences =
8102 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008103 // Current per-profile network preferences. This object follows the same threading rules as
8104 // the OEM network preferences above.
8105 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008106 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8107 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008108
lucaslin3ba7cc22022-12-19 02:35:33 +00008109 // Current VPN network preferences. This object follows the same threading rules as the OEM
8110 // network preferences above.
8111 @NonNull
8112 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8113 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8114
paulhu51f77dc2021-06-07 02:34:20 +00008115 // A set of UIDs that should use mobile data preferentially if available. This object follows
8116 // the same threading rules as the OEM network preferences above.
8117 @NonNull
8118 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8119
James Mattiscb1e0362021-04-06 17:07:42 -07008120 // OemNetworkPreferences activity String log entries.
8121 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8122 @NonNull
8123 private final LocalLog mOemNetworkPreferencesLogs =
8124 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8125
James Mattis02220e22021-03-13 19:27:21 -08008126 /**
8127 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8128 * @param packageName the package name to check existence of a mapping for.
8129 * @return true if a mapping exists, false otherwise
8130 */
8131 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8132 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8133 }
8134
James Mattise3ef1912020-12-20 11:09:58 -08008135 // The always-on request for an Internet-capable network that apps without a specific default
8136 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008137 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008138 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008139 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008140 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008141 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008142 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008143 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008144
James Mattisd31bdfa2020-12-23 16:37:26 -08008145 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8146 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8147 }
8148
8149 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008150 * Return the default network request currently tracking the given uid.
8151 * @param uid the uid to check.
8152 * @return the NetworkRequestInfo tracking the given uid.
8153 */
8154 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008155 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008156 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008157 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008158 // Checking the first request is sufficient as only multilayer requests will have more
8159 // than one request and for multilayer, all requests will track the same uids.
8160 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008161 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008162 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008163 highestPriorityNri = nri;
8164 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008165 }
8166 }
paulhuaa0743d2021-05-26 21:56:03 +08008167 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008168 }
8169
8170 /**
8171 * Get a copy of the network requests of the default request that is currently tracking the
8172 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008173 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8174 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008175 * @param requestorUid the uid to check the default for.
8176 * @param requestorPackageName the requestor's package name.
8177 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8178 */
8179 @NonNull
8180 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008181 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008182 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008183 getDefaultRequestTrackingUid(asUid).mRequests,
8184 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008185 }
8186
8187 /**
8188 * Copy the given nri's NetworkRequest collection.
8189 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008190 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8191 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008192 * @param requestorUid the uid to set on the copied collection.
8193 * @param requestorPackageName the package name to set on the copied collection.
8194 * @return the copied NetworkRequest collection.
8195 */
8196 @NonNull
8197 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008198 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8199 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008200 final List<NetworkRequest> requests = new ArrayList<>();
8201 for (final NetworkRequest nr : requestsToCopy) {
8202 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008203 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008204 nr.legacyType, nextNetworkRequestId(), nr.type));
8205 }
8206 return requests;
8207 }
8208
8209 @NonNull
8210 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008211 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8212 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008213 // These capabilities are for a TRACK_DEFAULT callback, so:
8214 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8215 // mDefaultRequest and a per-UID default request.
8216 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008217 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008218 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008219 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8220 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008221 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008222 restrictRequestUidsForCallerAndSetRequestorInfo(
8223 netCap, requestorUid, requestorPackageName);
8224 return netCap;
8225 }
8226
8227 /**
8228 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8229 * @param nr the network request to check for equality against.
8230 * @return the nri if one exists, null otherwise.
8231 */
8232 @Nullable
8233 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8234 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8235 if (nri.getNetworkRequestForCallback().equals(nr)) {
8236 return nri;
8237 }
8238 }
8239 return null;
8240 }
8241
8242 /**
8243 * Check if an nri is currently being managed by per-app default networking.
8244 * @param nri the nri to check.
8245 * @return true if this nri is currently being managed by per-app default networking.
8246 */
8247 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8248 // nri.mRequests.get(0) is only different from the original request filed in
8249 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8250 // functionality therefore if these two don't match, it means this particular nri is
8251 // currently being managed by a per-app default.
8252 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8253 }
8254
8255 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008256 * Determine if an nri is a managed default request that disallows default networking.
8257 * @param nri the request to evaluate
8258 * @return true if device-default networking is disallowed
8259 */
8260 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8261 // Check if this nri is a managed default that supports the default network at its
8262 // lowest priority request.
8263 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8264 final NetworkCapabilities lowestPriorityNetCap =
8265 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8266 return isPerAppDefaultRequest(nri)
8267 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8268 lowestPriorityNetCap));
8269 }
8270
Erik Kline05f2b402015-04-30 12:58:40 +09008271 // Request used to optionally keep mobile data active even when higher
8272 // priority networks like Wi-Fi are active.
8273 private final NetworkRequest mDefaultMobileDataRequest;
8274
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008275 // Request used to optionally keep wifi data active even when higher
8276 // priority networks like ethernet are active.
8277 private final NetworkRequest mDefaultWifiRequest;
8278
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008279 // Request used to optionally keep vehicle internal network always active
8280 private final NetworkRequest mDefaultVehicleRequest;
8281
James Mattisd31bdfa2020-12-23 16:37:26 -08008282 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8283 // network with no service. This NAI should never be matched against, nor should any public API
8284 // ever return the associated network. For this reason, this NAI is not in the list of available
8285 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8286 // default requests that don't support using the device default network which will ultimately
8287 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8288 @VisibleForTesting
8289 final NetworkAgentInfo mNoServiceNetwork;
8290
Chalard Jean5b409c72021-02-04 13:12:59 +09008291 // The NetworkAgentInfo currently satisfying the default request, if any.
8292 private NetworkAgentInfo getDefaultNetwork() {
8293 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008294 }
8295
James Mattis2516da32021-01-31 17:06:19 -08008296 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008297 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008298 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8299 // Currently, all network requests will have the same uids therefore checking the first
8300 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008301 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008302 if (null == uids) {
8303 continue;
8304 }
8305 for (final UidRange range : uids) {
8306 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008307 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008308 highestPriorityNri = nri;
8309 }
James Mattis2516da32021-01-31 17:06:19 -08008310 }
8311 }
8312 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008313 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008314 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008315 }
8316
Varun Ananddf569952019-02-06 10:13:38 -08008317 @Nullable
8318 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8319 return nai != null ? nai.network : null;
8320 }
8321
8322 private void ensureRunningOnConnectivityServiceThread() {
8323 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8324 throw new IllegalStateException(
8325 "Not running on ConnectivityService thread: "
8326 + Thread.currentThread().getName());
8327 }
8328 }
8329
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008330 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008331 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8332 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008333 }
8334
Chalard Jean29d06db2018-05-02 21:14:54 +09008335 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008336 * Returns whether local agents are supported on this device.
8337 *
8338 * Local agents are supported from U on TVs, and from V on all devices.
8339 */
8340 @VisibleForTesting
8341 public boolean areLocalAgentsSupported() {
8342 final PackageManager pm = mContext.getPackageManager();
8343 // Local agents are supported starting on U on TVs and on V on everything else.
8344 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8345 }
8346
8347 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008348 * Register a new agent with ConnectivityService to handle a network.
8349 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008350 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008351 * @param networkInfo the initial info associated with this network. It can be updated later :
8352 * see {@link #updateNetworkInfo}.
8353 * @param linkProperties the initial link properties of this network. They can be updated
8354 * later : see {@link #updateLinkProperties}.
8355 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008356 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008357 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008358 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008359 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008360 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008361 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008362 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008363 public Network registerNetworkAgent(INetworkAgent na,
8364 NetworkInfo networkInfo,
8365 LinkProperties linkProperties,
8366 NetworkCapabilities networkCapabilities,
8367 @NonNull NetworkScore initialScore,
8368 @Nullable LocalNetworkConfig localNetworkConfig,
8369 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008370 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008371 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8372 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8373 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008374 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008375 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008376 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008377 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008378 } else {
8379 enforceNetworkFactoryPermission();
8380 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008381 final boolean hasLocalCap =
8382 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8383 if (hasLocalCap && !areLocalAgentsSupported()) {
8384 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8385 throw new IllegalArgumentException("Local agents are not supported in this version");
8386 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008387 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8388 if (hasLocalCap != hasLocalNetworkConfig) {
8389 throw new IllegalArgumentException(null != localNetworkConfig
8390 ? "Only local network agents can have a LocalNetworkConfig"
8391 : "Local network agents must have a LocalNetworkConfig"
8392 );
8393 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008394
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008395 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008396 final long token = Binder.clearCallingIdentity();
8397 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008398 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008399 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8400 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008401 } finally {
8402 Binder.restoreCallingIdentity(token);
8403 }
8404 }
8405
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008406 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008407 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008408 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8409 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008410 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008411
Chalard Jeandbc46952022-02-02 00:14:18 +09008412 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8413 // and mutate them at any time.
8414 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8415 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8416 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008417 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008418
Chalard Jean366c5252022-01-25 18:27:53 +09008419 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008420 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008421 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8422 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008423 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008424 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008425 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8426 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8427 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008428
Chalard Jeandbc46952022-02-02 00:14:18 +09008429 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008430 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008431 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008432 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008433 mDeps.getNetworkStack().makeNetworkMonitor(
8434 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008435 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8436 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008437 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008438 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008439 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008440 }
8441
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008442 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008443 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008444 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008445 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008446 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008447 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8448 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8449 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008450
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008451 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008452
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008453 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008454 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008455 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008456 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008457
8458 try {
8459 networkMonitor.start();
8460 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008461 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008462 }
Chalard Jean366c5252022-01-25 18:27:53 +09008463
Chalard Jean1e4c2182023-10-06 18:45:53 +09008464 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008465 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008466 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008467 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008468 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008469 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008470 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008471 }
8472
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008473 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8474 @NonNull public final NetworkOffer offer;
8475
8476 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8477 this.offer = offer;
8478 }
8479
8480 @Override
8481 public void binderDied() {
8482 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8483 }
8484 }
8485
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008486 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8487 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8488 if (npi.providerId == providerId) return true;
8489 }
8490 return false;
8491 }
8492
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008493 /**
8494 * Register or update a network offer.
8495 * @param newOffer The new offer. If the callback member is the same as an existing
8496 * offer, it is an update of that offer.
8497 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008498 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008499 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8500 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008501 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008502 // This may actually happen if a provider updates its score or registers and then
8503 // immediately unregisters. The offer would still be in the handler queue, but the
8504 // provider would have been removed.
8505 if (DBG) log("Received offer from an unregistered provider");
8506 return;
8507 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008508 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8509 if (null != existingOffer) {
8510 handleUnregisterNetworkOffer(existingOffer);
8511 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008512 if (DBG) {
8513 // handleUnregisterNetworkOffer has already logged the old offer
8514 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8515 }
8516 } else {
8517 if (DBG) {
8518 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8519 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008520 }
8521 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8522 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008523 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008524 } catch (RemoteException e) {
8525 noi.binderDied();
8526 return;
8527 }
8528 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008529 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008530 }
8531
8532 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8533 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008534 if (DBG) {
8535 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8536 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008537
8538 // If the provider removes the offer and dies immediately afterwards this
8539 // function may be called twice in a row, but the array will no longer contain
8540 // the offer.
8541 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008542 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008543 }
8544
8545 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8546 @NonNull final INetworkOfferCallback callback) {
8547 ensureRunningOnConnectivityServiceThread();
8548 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008549 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008550 }
8551 return null;
8552 }
8553
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008554 /**
8555 * Called when receiving LinkProperties directly from a NetworkAgent.
8556 * Stores into |nai| any data coming from the agent that might also be written to the network's
8557 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8558 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008559 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008560 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008561 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8562 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008563 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008564 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008565 }
8566
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008567 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008568 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008569 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008570
Lorenzo Colittid523d142020-04-01 20:16:30 +09008571 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8572 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8573 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008574 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008575
Suprabh Shukla1e312032023-01-24 03:36:37 -08008576 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008577
8578 // update filtering rules, need to happen after the interface update so netd knows about the
8579 // new interface (the interface name -> index map becomes initialized)
8580 updateVpnFiltering(newLp, oldLp, networkAgent);
8581
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008582 updateMtu(newLp, oldLp);
8583 // TODO - figure out what to do for clat
8584// for (LinkProperties lp : newLp.getStackedLinks()) {
8585// updateMtu(lp, null);
8586// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008587 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008588 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008589 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8590 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008591
Erik Klineb9888902016-04-05 13:30:49 +09008592 updateRoutes(newLp, oldLp, netId);
8593 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008594 // Make sure LinkProperties represents the latest private DNS status.
8595 // This does not need to be done before updateDnses because the
8596 // LinkProperties are not the source of the private DNS configuration.
8597 // updateDnses will fetch the private DNS configuration from DnsManager.
8598 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008599
Chalard Jean5b409c72021-02-04 13:12:59 +09008600 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008601 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008602 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008603 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008604 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008605
8606 updateWakeOnLan(newLp);
8607
Hai Shalome58bdc62021-01-11 18:45:34 -08008608 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8609 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8610 // does, it needs to be merged here.
8611 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8612 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008613
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008614 // TODO - move this check to cover the whole function
8615 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008616 synchronized (networkAgent) {
8617 networkAgent.linkProperties = newLp;
8618 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008619 // Start or stop DNS64 detection and 464xlat according to network state.
8620 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008621 // Notify NSS when relevant events happened. Currently, NSS only cares about
8622 // interface changed to update clat interfaces accounting.
8623 final boolean interfacesChanged = oldLp == null
8624 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8625 if (interfacesChanged) {
8626 notifyIfacesChangedForNetworkStats();
8627 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008628 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8629 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008630 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008631 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008632
8633 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008634 }
8635
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008636 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8637 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8638 }
8639
Hai Shalome58bdc62021-01-11 18:45:34 -08008640 /**
8641 * @param naData captive portal data from NetworkAgent
8642 * @param apiData captive portal data from capport API
8643 */
8644 @Nullable
8645 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8646 CaptivePortalData apiData) {
8647 if (naData == null || apiData == null) {
8648 return naData == null ? apiData : naData;
8649 }
8650 final CaptivePortalData.Builder captivePortalBuilder =
8651 new CaptivePortalData.Builder(naData);
8652
8653 if (apiData.isCaptive()) {
8654 captivePortalBuilder.setCaptive(true);
8655 }
8656 if (apiData.isSessionExtendable()) {
8657 captivePortalBuilder.setSessionExtendable(true);
8658 }
8659 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8660 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8661 // otherwise data would be inconsistent. Prefer the capport API info if present,
8662 // as it can generally be refreshed more often.
8663 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8664 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8665 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8666 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8667 // No source has time / bytes remaining information: surface the newest refresh time
8668 // for other fields
8669 captivePortalBuilder.setRefreshTime(
8670 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8671 }
8672
Hai Shalom7c6ab402021-02-04 19:34:06 -08008673 // Prioritize the user portal URL from the network agent if the source is authenticated.
8674 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8675 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8676 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8677 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008678 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008679 // Prioritize the venue information URL from the network agent if the source is
8680 // authenticated.
8681 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8682 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8683 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8684 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008685 }
8686 return captivePortalBuilder.build();
8687 }
8688
Suprabh Shukla53e16392023-04-26 18:47:36 -07008689 @VisibleForTesting
8690 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008691 // This needs to be kept in sync and backwards compatible with the decoding logic in
8692 // NetdEventListenerService, which is non-mainline code.
8693 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8694 }
8695
Suprabh Shukla75642282023-04-25 23:15:43 -07008696 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8697 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8698 return true;
8699 }
8700 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8701 return true;
8702 }
8703 return false;
8704 }
8705
Suprabh Shukla1e312032023-01-24 03:36:37 -08008706 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008707 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008708 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008709 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008710 return;
8711 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008712
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008713 // Mask/mark of zero will not detect anything interesting.
8714 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008715 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008716 return;
8717 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008718
Suprabh Shukla1e312032023-01-24 03:36:37 -08008719 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008720 try {
8721 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008722 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008723 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008724 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008725 }
8726 } catch (Exception e) {
8727 loge("Exception modifying wakeup packet monitoring: " + e);
8728 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008729 }
8730
Junyu Lai970963e2022-10-25 15:46:47 +08008731 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008732 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008733 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008734 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008735 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008736 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008737 for (final String iface : interfaceDiff.added) {
8738 try {
8739 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008740 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008741 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008742 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008743 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008744 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008745 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008746 }
Paul Jensenbff73492014-04-28 10:33:11 -04008747 }
8748 }
Chalard Jean9589e722019-11-19 19:03:53 +09008749 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008750 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008751 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008752 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008753 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008754 } catch (Exception e) {
8755 loge("Exception removing interface: " + e);
8756 }
8757 }
8758 }
8759
Paul Jensene0fd4a82014-08-06 15:51:33 -04008760 /**
8761 * Have netd update routes from oldLp to newLp.
8762 * @return true if routes changed between oldLp and newLp
8763 */
Junyu Lai970963e2022-10-25 15:46:47 +08008764 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8765 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008766 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008767 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8768 new CompareOrUpdateResult<>(
8769 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008770 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008771 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008772
8773 // add routes before removing old in case it helps with continuous connectivity
8774
Chalard Jean9dd11612018-06-04 16:52:49 +09008775 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008776 for (RouteInfo route : routeDiff.added) {
8777 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008778 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008779 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008780 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008781 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008782 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008783 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008784 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008785 }
8786 }
8787 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008788 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008789 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008790 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008791 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008792 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008793 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008794 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008795 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008796 }
8797 }
8798
8799 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008800 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008801 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008802 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008803 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008804 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008805 }
8806 }
Tyler Weare4314862019-12-05 14:55:30 -08008807
8808 for (RouteInfo route : routeDiff.updated) {
8809 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8810 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008811 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008812 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008813 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008814 }
8815 }
8816 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8817 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008818 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008819
Junyu Lai970963e2022-10-25 15:46:47 +08008820 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8821 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008822 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8823 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008824 }
Erik Klineb9888902016-04-05 13:30:49 +09008825
Erik Kline31b4a9e2018-01-11 21:07:29 +09008826 if (DBG) {
8827 final Collection<InetAddress> dnses = newLp.getDnsServers();
8828 log("Setting DNS servers for network " + netId + " to " + dnses);
8829 }
Erik Klineb9888902016-04-05 13:30:49 +09008830 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008831 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008832 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008833 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008834 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008835 }
Erik Kline54e35c02017-04-07 15:29:29 +09008836 }
8837
Junyu Lai970963e2022-10-25 15:46:47 +08008838 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8839 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008840 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8841 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008842 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8843 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008844
8845 if (!wasFiltering && !needsFiltering) {
8846 // Nothing to do.
8847 return;
8848 }
8849
8850 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8851 // Nothing changed.
8852 return;
8853 }
8854
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008855 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008856 if (ranges == null || ranges.isEmpty()) {
8857 return;
8858 }
8859
Qingxi Libb8da982020-01-17 17:54:27 -08008860 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008861 // TODO: this create a window of opportunity for apps to receive traffic between the time
8862 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008863 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008864 // old rules are being removed.
8865 if (wasFiltering) {
8866 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8867 }
8868 if (needsFiltering) {
8869 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8870 }
8871 }
8872
Valentin Iftime9fa35092019-09-24 13:32:13 +02008873 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008874 if (mWolSupportedInterfaces == null) {
8875 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008876 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008877 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008878 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8879 }
8880
Luke Huangb913c812018-08-24 20:33:16 +08008881 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008882 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008883 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008884 }
8885 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008886 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008887 }
Luke Huangb913c812018-08-24 20:33:16 +08008888 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008889 }
8890
Chalard Jean62edfd82019-12-02 18:39:29 +09008891 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8892 @NonNull final NetworkCapabilities newNc) {
8893 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8894 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008895 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008896 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008897 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008898 } catch (RemoteException | ServiceSpecificException e) {
8899 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008900 }
8901 }
8902 }
8903
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008904 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008905 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008906 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008907 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008908 underlyingNetworks = underlyingNetworksOrDefault(
8909 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008910 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008911 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8912 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008913 // metered if any underlying is metered, or originally declared metered by the agent.
8914 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008915 boolean roaming = false; // roaming if any underlying is roaming
8916 boolean congested = false; // congested if any underlying is congested
8917 boolean suspended = true; // suspended if all underlying are suspended
8918
8919 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008920 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008921 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008922 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008923 for (Network underlyingNetwork : underlyingNetworks) {
8924 final NetworkAgentInfo underlying =
8925 getNetworkAgentInfoForNetwork(underlyingNetwork);
8926 if (underlying == null) continue;
8927
8928 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8929 hadUnderlyingNetworks = true;
8930 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008931 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008932 }
8933
8934 // Merge capabilities of this underlying network. For bandwidth, assume the
8935 // worst case.
8936 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8937 underlyingCaps.getLinkDownstreamBandwidthKbps());
8938 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8939 underlyingCaps.getLinkUpstreamBandwidthKbps());
8940 // If this underlying network is metered, the VPN is metered (it may cost money
8941 // to send packets on this network).
8942 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8943 // If this underlying network is roaming, the VPN is roaming (the billing structure
8944 // is different than the usual, local one).
8945 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8946 // If this underlying network is congested, the VPN is congested (the current
8947 // condition of the network affects the performance of this network).
8948 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8949 // If this network is not suspended, the VPN is not suspended (the VPN
8950 // is able to transfer some data).
8951 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008952 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008953 }
8954 }
8955 if (!hadUnderlyingNetworks) {
8956 // No idea what the underlying networks are; assume reasonable defaults
8957 metered = true;
8958 roaming = false;
8959 congested = false;
8960 suspended = false;
8961 }
8962
Chalard Jean1d420b32022-10-12 16:39:37 +09008963 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008964 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8965 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8966 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8967 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8968 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8969 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008970 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008971 }
8972
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008973 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008974 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8975 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8976 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008977 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008978 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008979 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008980 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008981 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8982 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008983 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008984 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008985 if (nai.everConnected()
8986 && !nai.isVPN()
8987 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008988 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008989 // does not cause any request (that is not a listen) currently matching that agent to
8990 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008991 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008992 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008993 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008994 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008995 }
8996
Paul Jensen53f08952015-06-16 14:27:36 -04008997 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008998 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008999 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009000 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04009001 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009002 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04009003 }
Chalard Jean254bd162022-08-25 13:04:51 +09009004 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009005 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009006 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009007 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009008 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009009 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009010 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009011 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009012 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009013 }
Chalard Jean254bd162022-08-25 13:04:51 +09009014 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08009015 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9016 } else {
9017 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9018 }
lucasline117e2e2019-10-22 18:27:33 +08009019 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009020
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009021 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09009022 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
9023 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009024 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09009025 }
9026
Lorenzo Colittibd079452021-07-02 11:47:57 +09009027 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09009028 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09009029 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009030 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009031 }
9032
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009033 return newNc;
9034 }
9035
Lorenzo Colitti44840702021-01-11 22:27:57 +09009036 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
9037 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
9038 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9039 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9040 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9041 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9042 if (prevSuspended != suspended) {
9043 // TODO (b/73132094) : remove this call once the few users of onSuspended and
9044 // onResumed have been removed.
9045 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
9046 : ConnectivityManager.CALLBACK_RESUMED);
9047 }
9048 if (prevSuspended != suspended || prevRoaming != roaming) {
9049 // updateNetworkInfo will mix in the suspended info from the capabilities and
9050 // take appropriate action for the network having possibly changed state.
9051 updateNetworkInfo(nai, nai.networkInfo);
9052 }
9053 }
9054
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009055 /**
9056 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
9057 *
9058 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
9059 * capabilities we manage and store in {@code nai}, such as validated status and captive
9060 * portal status)
9061 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
9062 * potentially triggers rematches.
9063 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
9064 * change.)
9065 *
9066 * @param oldScore score of the network before any of the changes that prompted us
9067 * to call this function.
9068 * @param nai the network having its capabilities updated.
9069 * @param nc the new network capabilities.
9070 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009071 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09009072 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009073 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009074 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009075 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9076 if (null != differences) {
9077 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9078 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009079 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009080 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009081
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009082 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009083 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009084 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009085
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009086 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009087 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9088 // the change we're processing can't affect any requests, it can only affect the listens
9089 // on this network. We might have been called by rematchNetworkAndRequests when a
9090 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009091 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009092 } else {
9093 // If the requestable capabilities have changed or the score changed, we can't have been
9094 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009095 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009096 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009097 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009098 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009099
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009100 final boolean oldMetered = prevNc.isMetered();
9101 final boolean newMetered = newNc.isMetered();
9102 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009103
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009104 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009105 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9106 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009107 }
junyulaif2c67e42018-08-07 19:50:45 +08009108
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009109 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9110 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009111
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009112 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009113 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009114 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009115 }
9116
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009117 // This network might have been underlying another network. Propagate its capabilities.
9118 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009119
Ken Chen5a35cf92023-10-07 07:54:22 +08009120 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009121 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009122 }
lucaslin53e8a262021-06-08 01:43:59 +08009123
9124 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009125 }
9126
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009127 /** Convenience method to update the capabilities for a given network. */
9128 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009129 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009130 }
9131
Yang Sun29037f62023-12-04 10:31:58 +08009132 private void maybeApplyMulticastRoutingConfig(@NonNull final NetworkAgentInfo nai,
9133 final LocalNetworkConfig oldConfig,
9134 final LocalNetworkConfig newConfig) {
9135 final MulticastRoutingConfig oldUpstreamConfig =
9136 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9137 oldConfig.getUpstreamMulticastRoutingConfig();
9138 final MulticastRoutingConfig oldDownstreamConfig =
9139 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9140 oldConfig.getDownstreamMulticastRoutingConfig();
9141 final MulticastRoutingConfig newUpstreamConfig =
9142 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9143 newConfig.getUpstreamMulticastRoutingConfig();
9144 final MulticastRoutingConfig newDownstreamConfig =
9145 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9146 newConfig.getDownstreamMulticastRoutingConfig();
9147
9148 if (oldUpstreamConfig.equals(newUpstreamConfig) &&
9149 oldDownstreamConfig.equals(newDownstreamConfig)) {
9150 return;
9151 }
9152
9153 final String downstreamNetworkName = nai.linkProperties.getInterfaceName();
9154 final LocalNetworkInfo lni = localNetworkInfoForNai(nai);
9155 final Network upstreamNetwork = lni.getUpstreamNetwork();
9156
9157 if (upstreamNetwork != null) {
9158 final String upstreamNetworkName =
9159 getLinkProperties(upstreamNetwork).getInterfaceName();
9160 applyMulticastRoutingConfig(downstreamNetworkName, upstreamNetworkName, newConfig);
9161 }
9162 }
9163
9164 private void applyMulticastRoutingConfig(@NonNull String localNetworkInterfaceName,
9165 @NonNull String upstreamNetworkInterfaceName,
9166 @NonNull final LocalNetworkConfig config) {
Yang Sunca537d52024-01-19 12:53:50 +08009167 if (mMulticastRoutingCoordinatorService == null) {
9168 if (config.getDownstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE ||
9169 config.getUpstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE) {
9170 loge("Multicast routing is not supported, failed to configure " + config
9171 + " for " + localNetworkInterfaceName + " to "
9172 + upstreamNetworkInterfaceName);
9173 }
9174 return;
9175 }
Yang Sun29037f62023-12-04 10:31:58 +08009176
9177 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9178 upstreamNetworkInterfaceName, config.getUpstreamMulticastRoutingConfig());
9179 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9180 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9181 config.getDownstreamMulticastRoutingConfig());
9182 }
9183
9184 private void disableMulticastRouting(@NonNull String localNetworkInterfaceName,
9185 @NonNull String upstreamNetworkInterfaceName) {
Yang Sunca537d52024-01-19 12:53:50 +08009186 if (mMulticastRoutingCoordinatorService == null) {
9187 return;
9188 }
Yang Sun29037f62023-12-04 10:31:58 +08009189
9190 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9191 upstreamNetworkInterfaceName, MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9192 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9193 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9194 MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9195 }
9196
Chalard Jean1e4c2182023-10-06 18:45:53 +09009197 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009198 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009199 @Nullable final LocalNetworkConfig oldConfig,
9200 @NonNull final LocalNetworkConfig newConfig) {
9201 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009202 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9203 return;
9204 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009205
Chalard Jean4fe23392023-10-17 23:02:27 +09009206 if (VDBG) {
9207 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9208 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009209 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
Chalard Jean1e4c2182023-10-06 18:45:53 +09009210 configBuilder.setUpstreamMulticastRoutingConfig(
9211 newConfig.getUpstreamMulticastRoutingConfig());
9212 configBuilder.setDownstreamMulticastRoutingConfig(
9213 newConfig.getDownstreamMulticastRoutingConfig());
9214
9215 final NetworkRequest oldRequest =
9216 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9217 final NetworkCapabilities oldCaps =
9218 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9219 final NetworkRequestInfo oldNri =
9220 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9221 final NetworkAgentInfo oldSatisfier =
9222 null == oldNri ? null : oldNri.getSatisfier();
9223 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9224 final NetworkCapabilities newCaps =
9225 (null == newRequest) ? null : newRequest.networkCapabilities;
9226 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9227 if (null != oldRequest && requestUpdated) {
9228 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9229 if (null == newRequest && null != oldSatisfier) {
9230 // If there is an old satisfier, but no new request, then remove the old upstream.
9231 removeLocalNetworkUpstream(nai, oldSatisfier);
9232 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009233 // When there is a new request, the rematch sees the new request and sends the
9234 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9235 // But here there is no new request, so the rematch won't see anything. Send
9236 // callbacks to apps now to tell them about the loss of upstream.
9237 notifyNetworkCallbacks(nai,
9238 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009239 return;
9240 }
9241 }
9242 if (null != newRequest && requestUpdated) {
9243 // File the new request if :
9244 // - it has changed (requestUpdated), or
9245 // - it's the first time this local info (null == oldConfig)
9246 // is updated and the request has not been filed yet.
9247 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9248 // upstream (the best) but never request it to be brought up.
9249 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9250 nextNetworkRequestId(), LISTEN_FOR_BEST);
9251 configBuilder.setUpstreamSelector(nr);
9252 final NetworkRequestInfo nri = new NetworkRequestInfo(
9253 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9254 0 /* callbackFlags */, null /* attributionTag */);
9255 if (null != oldSatisfier) {
9256 // Set the old satisfier in the new NRI so that the rematch will see any changes
9257 nri.setSatisfier(oldSatisfier, nr);
9258 }
9259 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009260 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9261 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9262 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009263 handleRegisterNetworkRequest(nri);
9264 } else {
9265 configBuilder.setUpstreamSelector(oldRequest);
9266 nai.localNetworkConfig = configBuilder.build();
9267 }
Yang Sun29037f62023-12-04 10:31:58 +08009268 maybeApplyMulticastRoutingConfig(nai, oldConfig, newConfig);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009269 }
9270
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009271 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009272 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009273 *
9274 * Ingress interface filtering enforces that all apps under the given network can only receive
9275 * packets from the network's interface (and loopback). This is important for VPNs because
9276 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9277 * non-VPN interfaces.
9278 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009279 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009280 * 1. the network is an app VPN (not legacy VPN)
9281 * 2. the VPN does not allow bypass
9282 * 3. the VPN is fully-routed
9283 * 4. the VPN interface is non-null
9284 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009285 * @see INetd#firewallAddUidInterfaceRules
9286 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009287 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009288 @Nullable
9289 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009290 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009291 if (nc == null || lp == null) return null;
9292 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009293 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009294 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009295 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009296 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009297 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009298 && !lp.hasExcludeRoute()) {
9299 return lp.getInterfaceName();
9300 }
9301 return null;
9302 }
9303
9304 /**
9305 * Returns whether we need to set interface filtering rule or not
9306 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009307 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009308 String isolationIface) {
9309 // Allow rules are always needed if VPN isolation is enabled.
9310 if (isolationIface != null) return true;
9311
9312 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9313 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9314 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009315 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009316 }
9317
Chiachang Wang28afaff2020-12-10 22:24:47 +08009318 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9319 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9320 int index = 0;
9321 for (UidRange range : ranges) {
9322 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9323 index++;
9324 }
9325 return stableRanges;
9326 }
9327
Chalard Jeane6c95272022-01-25 21:04:21 +09009328 private static UidRangeParcel[] intsToUidRangeStableParcels(
9329 final @NonNull ArraySet<Integer> uids) {
9330 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9331 int index = 0;
9332 for (int uid : uids) {
9333 stableRanges[index] = new UidRangeParcel(uid, uid);
9334 index++;
9335 }
9336 return stableRanges;
9337 }
9338
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009339 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9340 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9341 for (int i = 0; i < ranges.length; i++) {
9342 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9343 }
9344 return stableRanges;
9345 }
9346
Motomu Utsumi93a22182023-03-16 17:04:21 +09009347 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009348 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009349 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9350 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009351 if (mDeps.isAtLeastU()) {
9352 final Set<Integer> exemptUidSet = new ArraySet<>();
9353 for (final int uid: exemptUids) {
9354 exemptUidSet.add(uid);
9355 }
9356 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9357 } else {
9358 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9359 }
Ken Chen5e65a852020-12-24 12:59:10 +08009360 } catch (Exception e) {
9361 loge("Exception in socket destroy: ", e);
9362 }
9363 }
9364 }
9365
paulhuaa0743d2021-05-26 21:56:03 +08009366 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009367 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009368 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9369 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9370 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009371 exemptUids[0] = VPN_UID;
9372 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009373 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9374
Motomu Utsumi6345e462023-03-13 13:24:50 +09009375 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009376 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009377 try {
9378 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009379 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009380 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009381 } else {
paulhu0e79d952021-06-09 16:11:35 +08009382 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009383 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009384 }
9385 } catch (Exception e) {
9386 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9387 " on netId " + nai.network.netId + ". " + e);
9388 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009389 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009390 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009391 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009392
lucaslin53e8a262021-06-08 01:43:59 +08009393 private boolean isProxySetOnAnyDefaultNetwork() {
9394 ensureRunningOnConnectivityServiceThread();
9395 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9396 final NetworkAgentInfo nai = nri.getSatisfier();
9397 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9398 return true;
9399 }
9400 }
9401 return false;
9402 }
9403
9404 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9405 NetworkCapabilities newNc) {
9406 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9407 // the proxy might be changed since the default network satisfied by the apps might also
9408 // changed.
9409 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9410 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009411 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9412 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009413 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009414 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9415 mProxyTracker.sendProxyBroadcast();
9416 }
9417 }
9418
Chalard Jeane6c95272022-01-25 21:04:21 +09009419 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9420 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009421 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9422 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009423 if (null == prevRanges) prevRanges = new ArraySet<>();
9424 if (null == newRanges) newRanges = new ArraySet<>();
9425 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9426
9427 prevRanges.removeAll(newRanges);
9428 newRanges.removeAll(prevRangesCopy);
9429
9430 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009431 // When updating the VPN uid routing rules, add the new range first then remove the old
9432 // range. If old range were removed first, there would be a window between the old
9433 // range being removed and the new range being added, during which UIDs contained
9434 // in both ranges are not subject to any VPN routing rules. Adding new range before
9435 // removing old range works because, unlike the filtering rules below, it's possible to
9436 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009437 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9438 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9439 // [1-5] & [1-2],[4-5] == [3]
9440 // Then we can do:
9441 // maybeCloseSockets([3])
9442 // mNetd.networkAddUidRanges([1-2],[4-5])
9443 // mNetd.networkRemoveUidRanges([1-5])
9444 // maybeCloseSockets([3])
9445 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9446 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009447 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009448 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009449 }
9450 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009451 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009452 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009453 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9454 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009455 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9456 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009457 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009458 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009459 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9460 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9461 // were added first and then newRanges got removed later, there would be only one uid
9462 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9463 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9464 // Note that this is in contrast with the (more robust) update of VPN routing rules
9465 // above, where the addition of new ranges happens before the removal of old ranges.
9466 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9467 // to be removed will never overlap with the new range to be added.
9468 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009469 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9470 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009471 }
9472 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009473 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009474 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009475 } catch (Exception e) {
9476 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009477 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009478 }
9479 }
9480
Chalard Jeande665262022-02-25 16:12:12 +09009481 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009482 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9483 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009484 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9485 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009486 if (prevEmpty && newEmpty) return;
9487
9488 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009489 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009490 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009491 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009492
9493 if (prevUids.equals(newUids)) return;
9494
9495 // This implementation is very simple and vastly faster for sets of Integers than
9496 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9497 // a key computed from the value and has storage for that.
9498 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9499 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9500 toRemove.removeAll(newUids);
9501 toAdd.removeAll(prevUids);
9502
9503 try {
9504 if (!toAdd.isEmpty()) {
9505 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9506 nai.network.netId,
9507 intsToUidRangeStableParcels(toAdd),
9508 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9509 }
9510 if (!toRemove.isEmpty()) {
9511 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9512 nai.network.netId,
9513 intsToUidRangeStableParcels(toRemove),
9514 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9515 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009516 } catch (ServiceSpecificException e) {
9517 // Has the interface disappeared since the network was built ?
9518 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009519 } catch (RemoteException e) {
9520 // Netd died. This usually causes a runtime restart anyway.
9521 }
9522 }
9523
Junyu Lai2ed7d412022-10-07 16:52:21 +08009524 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9525 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009526 ensureRunningOnConnectivityServiceThread();
9527
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009528 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009529 // Ignore updates for disconnected networks
9530 return;
9531 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009532 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009533 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009534 + "; created=" + nai.getCreatedTime()
9535 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009536 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009537 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9538 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009539 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009540 }
9541
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009542 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9543 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009544 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009545 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009546 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009547 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9548 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9549 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009550 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9551 // need to be sent as a separate extra.
9552 final NetworkRequest req = nri.isMultilayerRequest()
9553 ? nri.getActiveRequest()
9554 // Non-multilayer listen requests do not have an active request
9555 : nri.mRequests.get(0);
9556 if (req == null) {
9557 Log.wtf(TAG, "No request in NRI " + nri);
9558 }
9559 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009560 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009561 sendIntent(nri.mPendingIntent, intent);
9562 }
9563 // else not handled
9564 }
9565
Michael Groover73f69482023-01-27 11:01:25 -06009566 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9567 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009568 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9569 mPendingIntentWakeLock.acquire();
9570 try {
9571 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009572 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009573 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009574 // Explicitly disallow the receiver from starting activities, to prevent apps from
9575 // utilizing the PendingIntent as a backdoor to do this.
9576 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9577 }
9578 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9579 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009580 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009581 } catch (PendingIntent.CanceledException e) {
9582 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9583 mPendingIntentWakeLock.release();
9584 releasePendingNetworkRequest(pendingIntent);
9585 }
9586 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9587 }
9588
9589 @Override
9590 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9591 String resultData, Bundle resultExtras) {
9592 if (DBG) log("Finished sending " + pendingIntent);
9593 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009594 // Release with a delay so the receiving client has an opportunity to put in its
9595 // own request.
9596 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009597 }
9598
Chalard Jean22350c92023-10-07 19:21:45 +09009599 @Nullable
9600 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9601 if (!nai.isLocalNetwork()) return null;
9602 final Network upstream;
9603 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9604 if (null == selector) {
9605 upstream = null;
9606 } else {
9607 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9608 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9609 upstream = (null == satisfier) ? null : satisfier.network;
9610 }
9611 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9612 }
9613
Chalard Jean46bfbf02022-02-02 00:56:25 +09009614 // networkAgent is only allowed to be null if notificationType is
9615 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9616 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009617 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009618 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009619 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009620 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009621 // Default request has no msgr. Also prevents callbacks from being invoked for
9622 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9623 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9624 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009625 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009626 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009627 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009628 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009629 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009630 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009631 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009632 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9633 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009634 }
Roshan Pius951c0032020-12-22 15:10:42 -08009635 final boolean includeLocationSensitiveInfo =
9636 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009637 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009638 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009639 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009640 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009641 networkCapabilitiesRestrictedForCallerPermissions(
9642 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9643 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009644 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009645 nri.mCallingAttributionTag);
9646 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009647 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9648 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009649 // The local network info is often null, so can't use the static putParcelable
9650 // method here.
9651 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9652 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009653 // For this notification, arg1 contains the blocked status.
9654 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009655 break;
9656 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009657 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009658 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009659 break;
9660 }
9661 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009662 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009663 final NetworkCapabilities netCap =
9664 networkCapabilitiesRestrictedForCallerPermissions(
9665 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9666 putParcelable(
9667 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009668 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009669 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009670 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009671 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009672 break;
9673 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009674 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009675 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9676 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009677 break;
9678 }
junyulaif2c67e42018-08-07 19:50:45 +08009679 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009680 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009681 msg.arg1 = arg1;
9682 break;
9683 }
Chalard Jean22350c92023-10-07 19:21:45 +09009684 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9685 if (!networkAgent.isLocalNetwork()) {
9686 Log.wtf(TAG, "Callback for local info for a non-local network");
9687 return;
9688 }
9689 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9690 break;
9691 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009692 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009693 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009694 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009695 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009696 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009697 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009698 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009699 }
James Mattis45d81842021-01-10 14:24:24 -08009700 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009701 } catch (RemoteException e) {
9702 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009703 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009704 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009705 }
9706
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009707 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9708 bundle.putParcelable(t.getClass().getSimpleName(), t);
9709 }
9710
Chalard Jean0702f982021-09-16 21:50:07 +09009711 /**
9712 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9713 *
9714 * When a request should be assigned to a new network, it is normally lingered to give
9715 * time for apps to gracefully migrate their connections. When both networks are on the same
9716 * radio, but that radio can't do time-sharing efficiently, this may end up being
9717 * counter-productive because any traffic on the old network may drastically reduce the
9718 * performance of the new network.
9719 * The stack supports a configuration to let modem vendors state that their radio can't
9720 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9721 * from one cell network to another can't be done gracefully.
9722 *
9723 * @param oldNai the old network serving the request
9724 * @param newNai the new network serving the request
9725 * @return whether the switch can be graceful
9726 */
9727 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9728 @NonNull final NetworkAgentInfo newSatisfier) {
9729 if (mCellularRadioTimesharingCapable) return true;
9730 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9731 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9732 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9733 }
9734
Paul Jensenaf94b982014-09-30 15:37:41 -04009735 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009736 if (nai.numRequestNetworkRequests() != 0) {
9737 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9738 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009739 // Ignore listening and track default requests.
9740 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009741 loge("Dead network still had at least " + nr);
9742 break;
9743 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009744 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009745 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009746 }
9747
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009748 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9749 if (oldNetwork == null) {
9750 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9751 return;
9752 }
Chalard Jean49707572019-12-10 21:07:02 +09009753 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009754
9755 // If we get here it means that the last linger timeout for this network expired. So there
9756 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009757 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009758
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009759 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009760 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009761 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009762 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009763 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009764 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009765 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009766 }
9767
James Mattise3ef1912020-12-20 11:09:58 -08009768 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9769 boolean isDefaultChanged = false;
9770 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9771 final NetworkReassignment.RequestReassignment reassignment =
9772 changes.getReassignment(defaultRequestInfo);
9773 if (null == reassignment) {
9774 continue;
9775 }
9776 // reassignment only contains those instances where the satisfying network changed.
9777 isDefaultChanged = true;
9778 // Notify system services of the new default.
9779 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9780 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009781
James Mattise3ef1912020-12-20 11:09:58 -08009782 if (isDefaultChanged) {
9783 // Hold a wakelock for a short time to help apps in migrating to a new default.
9784 scheduleReleaseNetworkTransitionWakelock();
9785 }
9786 }
9787
Aaron Huang9fe47be2021-06-08 13:11:45 +08009788 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9789 if (null == oldDefaultNetwork) return;
9790 // The network stopped being the default. If it was using a PAC proxy, then the
9791 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9792 // to the local proxy server, which would forward them over the newly default network.
9793 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9794 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9795 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9796 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9797 }
9798
James Mattise3ef1912020-12-20 11:09:58 -08009799 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9800 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9801 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9802 if (DBG) {
9803 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9804 }
Chalard Jean8e382112019-12-03 20:45:30 +09009805
James Mattisd31bdfa2020-12-23 16:37:26 -08009806 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9807 if (newDefaultNetwork != null) {
9808 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009809 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009810
James Mattisd31bdfa2020-12-23 16:37:26 -08009811 // Set an app level managed default and return since further processing only applies to the
9812 // default network.
9813 if (mDefaultRequest != nri) {
9814 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9815 return;
9816 }
9817
9818 makeDefaultNetwork(newDefaultNetwork);
9819
James Mattise3ef1912020-12-20 11:09:58 -08009820 if (oldDefaultNetwork != null) {
9821 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9822 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009823 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009824 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009825 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009826 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009827 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009828 updateTcpBufferSizes(null != newDefaultNetwork
9829 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009830 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009831 }
9832
James Mattisd31bdfa2020-12-23 16:37:26 -08009833 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9834 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9835 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9836 try {
9837 if (VDBG) {
9838 log("Setting default network for " + nri
9839 + " using UIDs " + nri.getUids()
9840 + " with old network " + (oldDefaultNetwork != null
9841 ? oldDefaultNetwork.network().getNetId() : "null")
9842 + " and new network " + (newDefaultNetwork != null
9843 ? newDefaultNetwork.network().getNetId() : "null"));
9844 }
9845 if (nri.getUids().isEmpty()) {
9846 throw new IllegalStateException("makeDefaultForApps called without specifying"
9847 + " any applications to set as the default." + nri);
9848 }
9849 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009850 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009851 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009852 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009853 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009854 }
9855 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009856 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009857 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009858 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009859 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009860 }
9861 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009862 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009863 }
9864 }
9865
Junyu Lai35665cc2022-12-19 17:37:48 +08009866 /**
9867 * Collect restricted uid ranges for the given network and UserHandle, these uids
9868 * are not restricted for matched enterprise networks but being restricted for non-matched
9869 * enterprise networks and non-enterprise networks.
9870 */
9871 @NonNull
9872 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9873 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9874 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9875 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9876 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9877
9878 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9879 // The NC is built from a `ProfileNetworkPreference` which has only one
9880 // enterprise ID, so it's guaranteed to have exactly one.
9881 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9882 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9883 continue;
9884 }
9885 }
9886
9887 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9888 pref.capabilities.getUidRanges())) {
9889 throw new IllegalArgumentException(
9890 "Overlapping uid range in preference: " + pref);
9891 }
9892 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9893 }
9894 return restrictedUidRanges;
9895 }
9896
9897 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009898 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009899 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009900
Junyu Lai35665cc2022-12-19 17:37:48 +08009901 ensureRunningOnConnectivityServiceThread();
9902 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9903 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9904 .getUserHandles(true /* excludeDying */);
9905 if (users.isEmpty()) {
9906 throw new IllegalStateException("No user is available");
9907 }
9908
9909 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9910 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9911 for (final UserHandle user : users) {
9912 final ArraySet<UidRange> restrictedUidRanges =
9913 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9914 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9915 UidRange.createForUser(user), restrictedUidRanges));
9916 }
9917
9918 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9919 configs.add(new NativeUidRangeConfig(
9920 nai.network.netId, rangesParcel, 0 /* subPriority */));
9921 }
9922
9923 // The netd API replaces the previous configs with the current configs.
9924 // Thus, for network disconnection or preference removal, no need to
9925 // unset previous config. Instead, collecting all currently needed
9926 // configs and issue to netd.
9927 try {
9928 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9929 } catch (ServiceSpecificException e) {
9930 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009931 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009932 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009933 // Netd died. This will cause a runtime restart anyway.
9934 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009935 }
9936 }
9937
James Mattisd31bdfa2020-12-23 16:37:26 -08009938 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9939 try {
9940 if (null != newDefaultNetwork) {
9941 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9942 } else {
9943 mNetd.networkClearDefault();
9944 }
9945 } catch (RemoteException | ServiceSpecificException e) {
9946 loge("Exception setting default network :" + e);
9947 }
9948 }
9949
Chalard Jean05cbe972019-12-09 11:50:38 +09009950 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009951 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009952 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009953 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009954 processNewlySatisfiedListenRequests(nai);
9955 }
9956
9957 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009958 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9959 if (nri.isMultilayerRequest()) {
9960 continue;
9961 }
9962 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009963 if (!nr.isListen()) continue;
9964 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009965 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009966 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9967 }
9968 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009969 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009970
Chalard Jeancd397a22019-11-22 22:33:33 +09009971 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009972 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9973 if (nri.isMultilayerRequest()) {
9974 continue;
9975 }
9976 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009977 if (!nr.isListen()) continue;
9978 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9979 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009980 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009981 }
9982 }
9983 }
9984
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009985 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009986 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009987 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009988 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009989 @Nullable public final NetworkRequest mOldNetworkRequest;
9990 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009991 @Nullable public final NetworkAgentInfo mOldNetwork;
9992 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009993 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009994 @Nullable final NetworkRequest oldNetworkRequest,
9995 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009996 @Nullable final NetworkAgentInfo oldNetwork,
9997 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009998 mNetworkRequestInfo = networkRequestInfo;
9999 mOldNetworkRequest = oldNetworkRequest;
10000 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010001 mOldNetwork = oldNetwork;
10002 mNewNetwork = newNetwork;
10003 }
Chalard Jean49707572019-12-10 21:07:02 +090010004
10005 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +090010006 final NetworkRequest requestToShow = null != mNewNetworkRequest
10007 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
10008 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -080010009 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
10010 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +090010011 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010012 }
10013
Chalard Jean46a62372019-12-10 21:25:24 +090010014 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010015
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010016 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +090010017 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010018 }
10019
10020 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +090010021 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +090010022 // The code is never supposed to add two reassignments of the same request. Make
10023 // sure this stays true, but without imposing this expensive check on all
10024 // reassignments on all user devices.
10025 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -080010026 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +090010027 throw new IllegalStateException("Trying to reassign ["
10028 + reassignment + "] but already have ["
10029 + existing + "]");
10030 }
10031 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +090010032 }
Chalard Jean46a62372019-12-10 21:25:24 +090010033 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010034 }
10035
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010036 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +090010037 // the passed request.
10038 @Nullable
10039 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010040 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010041 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010042 }
10043 return null;
10044 }
Chalard Jean49707572019-12-10 21:07:02 +090010045
10046 public String toString() {
10047 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
10048 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +090010049 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010050 for (final RequestReassignment rr : getRequestReassignments()) {
10051 sj.add(rr.toString());
10052 }
10053 return sj.toString();
10054 }
10055
10056 public String debugString() {
10057 final StringBuilder sb = new StringBuilder();
10058 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +090010059 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010060 for (final RequestReassignment rr : getRequestReassignments()) {
10061 sb.append("\n ").append(rr);
10062 }
10063 return sb.append("\n").toString();
10064 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010065 }
10066
Chalard Jean24344d72019-12-04 13:32:31 +090010067 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010068 @Nullable final NetworkRequest previousRequest,
10069 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +090010070 @Nullable final NetworkAgentInfo previousSatisfier,
10071 @Nullable final NetworkAgentInfo newSatisfier,
10072 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -080010073 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +090010074 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +090010075 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010076 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010077 log(" accepting network in place of " + previousSatisfier.toShortString()
10078 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010079 }
James Mattisa076c532020-12-02 14:12:41 -080010080 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010081 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +090010082 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +090010083 // If this network switch can't be supported gracefully, the request is not
10084 // lingered. This allows letting go of the network sooner to reclaim some
10085 // performance on the new network, since the radio can't do both at the same
10086 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010087 //
10088 // Also don't linger the request if the old network has been destroyed.
10089 // A destroyed network does not provide actual network connectivity, so
10090 // lingering it is not useful. In particular this ensures that a destroyed
10091 // network is outscored by its replacement,
10092 // then it is torn down immediately instead of being lingered, and any apps that
10093 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +090010094 previousSatisfier.lingerRequest(previousRequest.requestId, now);
10095 }
Chalard Jean24344d72019-12-04 13:32:31 +090010096 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010097 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010098 }
junyulai0ac374f2020-12-14 18:41:52 +080010099
10100 // To prevent constantly CPU wake up for nascent timer, if a network comes up
10101 // and immediately satisfies a request then remove the timer. This will happen for
10102 // all networks except in the case of an underlying network for a VCN.
10103 if (newSatisfier.isNascent()) {
10104 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +080010105 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010106 }
10107
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010108 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -080010109 newSatisfier.unlingerRequest(newRequest.requestId);
10110 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +080010111 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -080010112 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010113 }
Chalard Jeana8ac2302021-03-01 22:16:08 +090010114 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010115 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010116 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -080010117 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010118 }
James Mattisa076c532020-12-02 14:12:41 -080010119 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010120 }
James Mattisa076c532020-12-02 14:12:41 -080010121 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010122 }
10123
James Mattisa076c532020-12-02 14:12:41 -080010124 /**
10125 * This function is triggered when something can affect what network should satisfy what
10126 * request, and it computes the network reassignment from the passed collection of requests to
10127 * network match to the one that the system should now have. That data is encoded in an
10128 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
10129 * satisfier.
10130 *
10131 * After the reassignment is computed, it is applied to the state objects.
10132 *
10133 * @param networkRequests the nri objects to evaluate for possible network reassignment
10134 * @return NetworkReassignment listing of proposed network assignment changes
10135 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010136 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080010137 private NetworkReassignment computeNetworkReassignment(
10138 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010139 final NetworkReassignment changes = new NetworkReassignment();
10140
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010141 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010142 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010143 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010144 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010145 }
Chalard Jean857a1712019-12-10 21:08:07 +090010146
James Mattisa076c532020-12-02 14:12:41 -080010147 for (final NetworkRequestInfo nri : networkRequests) {
10148 // Non-multilayer listen requests can be ignored.
10149 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10150 continue;
10151 }
10152 NetworkAgentInfo bestNetwork = null;
10153 NetworkRequest bestRequest = null;
10154 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010155 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010156 // Stop evaluating as the highest possible priority request is satisfied.
10157 if (null != bestNetwork) {
10158 bestRequest = req;
10159 break;
10160 }
10161 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010162 if (null == bestNetwork && isDefaultBlocked(nri)) {
10163 // Remove default networking if disallowed for managed default requests.
10164 bestNetwork = mNoServiceNetwork;
10165 }
10166 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010167 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010168 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010169 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010170 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010171 }
10172 return changes;
10173 }
10174
James Mattisa076c532020-12-02 14:12:41 -080010175 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10176 return new HashSet<>(mNetworkRequests.values());
10177 }
10178
Paul Jensenc88b39b2015-06-16 14:27:36 -040010179 /**
James Mattisa076c532020-12-02 14:12:41 -080010180 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010181 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010182 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010183 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010184 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10185 }
10186
10187 /**
10188 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10189 * being disconnected.
10190 */
10191 private void rematchNetworksAndRequests(
10192 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10193 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010194 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010195 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010196 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010197 final long computed = SystemClock.elapsedRealtime();
10198 applyNetworkReassignment(changes, start);
10199 final long applied = SystemClock.elapsedRealtime();
10200 issueNetworkNeeds();
10201 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010202 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010203 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10204 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010205 log(changes.debugString());
10206 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010207 // Shorter form, only one line of log
10208 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10209 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010210 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010211 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010212
Chalard Jean1e4c2182023-10-06 18:45:53 +090010213 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10214 @Nullable final NetworkAgentInfo nai2) {
10215 if (null == nai1) return null == nai2;
10216 if (null == nai2) return false;
10217 return nai1.linkProperties.getInterfaceName()
10218 .equals(nai2.linkProperties.getInterfaceName());
10219 }
10220
Chalard Jeand7f762d2019-12-10 19:01:29 +090010221 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010222 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010223 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010224
10225 // Since most of the time there are only 0 or 1 background networks, it would probably
10226 // be more efficient to just use an ArrayList here. TODO : measure performance
10227 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10228 for (final NetworkAgentInfo nai : nais) {
10229 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10230 }
10231
Chalard Jeand7f762d2019-12-10 19:01:29 +090010232 // First, update the lists of satisfied requests in the network agents. This is necessary
10233 // because some code later depends on this state to be correct, most prominently computing
10234 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010235 for (final NetworkReassignment.RequestReassignment event :
10236 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010237 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10238 event.mOldNetworkRequest, event.mNewNetworkRequest,
10239 event.mOldNetwork, event.mNewNetwork,
10240 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010241 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010242
James Mattise3ef1912020-12-20 11:09:58 -080010243 // Process default network changes if applicable.
10244 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010245
Chalard Jean68eab722023-11-16 17:00:04 +090010246 // Update forwarding rules for the upstreams of local networks. Do this before sending
10247 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10248 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10249 // onAvailable so clients know what network the change is about. Store such changes in
10250 // an array that's only allocated if necessary (because it's almost never necessary).
10251 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10252 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10253 if (!nai.isLocalNetwork()) continue;
10254 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10255 if (null == nr) continue; // No upstream for this local network
10256 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10257 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10258 if (null == change) continue; // No change in upstreams for this network
10259 final String fromIface = nai.linkProperties.getInterfaceName();
10260 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10261 || change.mOldNetwork.isDestroyed()) {
10262 // There can be a change with the same interface name if the new network is the
10263 // replacement for the old network that was unregisteredAfterReplacement.
10264 try {
10265 if (null != change.mOldNetwork) {
10266 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10267 change.mOldNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010268 disableMulticastRouting(fromIface,
10269 change.mOldNetwork.linkProperties.getInterfaceName());
Chalard Jean68eab722023-11-16 17:00:04 +090010270 }
10271 // If the new upstream is already destroyed, there is no point in setting up
10272 // a forward (in fact, it might forward to the interface for some new network !)
10273 // Later when the upstream disconnects CS will try to remove the forward, which
10274 // is ignored with a benign log by RoutingCoordinatorService.
10275 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10276 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10277 change.mNewNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010278 applyMulticastRoutingConfig(fromIface,
10279 change.mNewNetwork.linkProperties.getInterfaceName(),
10280 nai.localNetworkConfig);
Chalard Jean68eab722023-11-16 17:00:04 +090010281 }
10282 } catch (final RemoteException e) {
10283 loge("Can't update forwarding rules", e);
10284 }
10285 }
10286 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10287 localInfoChangedAgents.add(nai);
10288 }
10289
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010290 // Notify requested networks are available after the default net is switched, but
10291 // before LegacyTypeTracker sends legacy broadcasts
10292 for (final NetworkReassignment.RequestReassignment event :
10293 changes.getRequestReassignments()) {
10294 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010295 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010296 } else {
James Mattisa076c532020-12-02 14:12:41 -080010297 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010298 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010299 }
10300 }
10301
junyulai0ac374f2020-12-14 18:41:52 +080010302 // Update the inactivity state before processing listen callbacks, because the background
10303 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010304 // just yet though, because they have to be sent after the listens are processed to keep
10305 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010306 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010307 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010308 // Rematching may have altered the inactivity state of some networks, so update all
10309 // inactivity timers. updateInactivityState reads the state from the network agent
10310 // and does nothing if the state has not changed : the source of truth is controlled
10311 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10312 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010313 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010314 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010315 }
10316 }
10317
Chalard Jeanb10ab412019-12-11 14:12:30 +090010318 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010319 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010320 // Process listen requests and update capabilities if the background state has
10321 // changed for this network. For consistency with previous behavior, send onLost
10322 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010323 processNewlyLostListenRequests(nai);
10324 if (oldBackground != nai.isBackgroundNetwork()) {
10325 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010326 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010327 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010328 }
10329
junyulai0ac374f2020-12-14 18:41:52 +080010330 for (final NetworkAgentInfo nai : inactiveNetworks) {
10331 // For nascent networks, if connecting with no foreground request, skip broadcasting
10332 // LOSING for backward compatibility. This is typical when mobile data connected while
10333 // wifi connected with mobile data always-on enabled.
10334 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010335 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010336 }
10337
Chalard Jean68eab722023-11-16 17:00:04 +090010338 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10339 if (null != localInfoChangedAgents) {
10340 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10341 notifyNetworkCallbacks(nai,
10342 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010343 }
10344 }
10345
James Mattise3ef1912020-12-20 11:09:58 -080010346 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010347
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010348 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010349 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010350 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010351 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010352 // This network has active linger timers and no requests, but is not
10353 // lingering. Linger it.
10354 //
10355 // One way (the only way?) this can happen if this network is unvalidated
10356 // and became unneeded due to another network improving its score to the
10357 // point where this network will no longer be able to satisfy any requests
10358 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010359 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010360 notifyNetworkLosing(nai, now);
10361 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010362 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010363 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010364 teardownUnneededNetwork(nai);
10365 }
10366 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010367 }
10368 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010369
Chalard Jean62edfd82019-12-02 18:39:29 +090010370 /**
10371 * Apply a change in background state resulting from rematching networks with requests.
10372 *
10373 * During rematch, a network may change background states by starting to satisfy or stopping
10374 * to satisfy a foreground request. Listens don't count for this. When a network changes
10375 * background states, its capabilities need to be updated and callbacks fired for the
10376 * capability change.
10377 *
10378 * @param nai The network that changed background states
10379 */
10380 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10381 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10382 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10383 updateNetworkPermissions(nai, newNc);
10384 nai.getAndSetNetworkCapabilities(newNc);
10385 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10386 }
10387
Chalard Jeanf0344532019-11-19 19:23:38 +090010388 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010389 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010390 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010391 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10392 changes.getReassignment(mDefaultRequest);
10393 final NetworkAgentInfo oldDefaultNetwork =
10394 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10395 final NetworkAgentInfo newDefaultNetwork =
10396 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010397
Chalard Jean5b409c72021-02-04 13:12:59 +090010398 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010399 // Maintain the illusion : since the legacy API only understands one network at a time,
10400 // if the default network changed, apps should see a disconnected broadcast for the
10401 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010402 if (oldDefaultNetwork != null) {
10403 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10404 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010405 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010406 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010407 // The new default network can be newly null if and only if the old default
10408 // network doesn't satisfy the default request any more because it lost a
10409 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010410 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010411 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010412 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010413 }
10414 }
10415
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010416 // Now that all the callbacks have been sent, send the legacy network broadcasts
10417 // as needed. This is necessary so that legacy requests correctly bind dns
10418 // requests to this network. The legacy users are listening for this broadcast
10419 // and will generally do a dns request so they can ensureRouteToHost and if
10420 // they do that before the callbacks happen they'll use the default network.
10421 //
10422 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10423 // callbacks, but if apps can receive the broadcast before the callback, they still might
10424 // have an inconsistent view of networking.
10425 //
10426 // This *does* introduce a race where if the user uses the new api
10427 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10428 // they may get old info. Reverse this after the old startUsing api is removed.
10429 // This is on top of the multiple intent sequencing referenced in the todo above.
10430 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010431 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010432 addNetworkToLegacyTypeTracker(nai);
10433 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010434 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010435 }
10436
Chalard Jean0354d8c2021-01-12 10:58:56 +090010437 private void issueNetworkNeeds() {
10438 ensureRunningOnConnectivityServiceThread();
10439 for (final NetworkOfferInfo noi : mNetworkOffers) {
10440 issueNetworkNeeds(noi);
10441 }
10442 }
10443
10444 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10445 ensureRunningOnConnectivityServiceThread();
10446 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10447 informOffer(nri, noi.offer, mNetworkRanker);
10448 }
10449 }
10450
10451 /**
10452 * Inform a NetworkOffer about any new situation of a request.
10453 *
10454 * This function handles updates to offers. A number of events may happen that require
10455 * updating the registrant for this offer about the situation :
10456 * • The offer itself was updated. This may lead the offer to no longer being able
10457 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10458 * or conversely being strengthened enough to beat the satisfier (and therefore
10459 * start being needed)
10460 * • The network satisfying a request changed (including cases where the request
10461 * starts or stops being satisfied). The new network may be a stronger or weaker
10462 * match than the old one, possibly affecting whether the offer is needed.
10463 * • The network satisfying a request updated their score. This may lead the offer
10464 * to no longer be able to beat it if the current satisfier got better, or
10465 * conversely start being a good choice if the current satisfier got weaker.
10466 *
10467 * @param nri The request
10468 * @param offer The offer. This may be an updated offer.
10469 */
10470 private static void informOffer(@NonNull NetworkRequestInfo nri,
10471 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10472 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10473 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010474
10475 // Multi-layer requests have a currently active request, the one being satisfied.
10476 // Since the system will try to bring up a better network than is currently satisfying
10477 // the request, NetworkProviders need to be told the offers matching the requests *above*
10478 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10479 // not needed, and the offer is needed for the active request iff the offer can beat
10480 // the satisfier.
10481 // For non-multilayer requests, the logic above gracefully degenerates to only the
10482 // last case.
10483 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10484 // providers that the offer is needed for this request, until the active request is found.
10485 // In a second phase, deal with the currently active request. In a third phase, inform
10486 // the providers that offer is unneeded for the remaining requests.
10487
10488 // First phase : inform providers of all requests above the active request.
10489 int i;
10490 for (i = 0; nri.mRequests.size() > i; ++i) {
10491 final NetworkRequest request = nri.mRequests.get(i);
10492 if (activeRequest == request) break; // Found the active request : go to phase 2
10493 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10494 // Since this request is higher-priority than the one currently satisfied, if the
10495 // offer can satisfy it, the provider should try and bring up the network for sure ;
10496 // no need to even ask the ranker – an offer that can satisfy is always better than
10497 // no network. Hence tell the provider so unless it already knew.
10498 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10499 offer.onNetworkNeeded(request);
10500 }
10501 }
10502
10503 // Second phase : deal with the active request (if any)
10504 if (null != activeRequest && activeRequest.isRequest()) {
10505 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010506 // If an offer can satisfy the request, it is considered needed if it is currently
10507 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010508 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010509 && satisfier.factorySerialNumber == offer.providerId
10510 && activeRequest.canBeSatisfiedBy(offer.caps);
10511 final boolean newNeeded = currentlyServing
10512 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010513 if (newNeeded != oldNeeded) {
10514 if (newNeeded) {
10515 offer.onNetworkNeeded(activeRequest);
10516 } else {
10517 // The offer used to be able to beat the satisfier. Now it can't.
10518 offer.onNetworkUnneeded(activeRequest);
10519 }
10520 }
10521 }
10522
10523 // Third phase : inform the providers that the offer isn't needed for any request
10524 // below the active one.
10525 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10526 final NetworkRequest request = nri.mRequests.get(i);
10527 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10528 // Since this request is lower-priority than the one currently satisfied, if the
10529 // offer can satisfy it, the provider should not try and bring up the network.
10530 // Hence tell the provider so unless it already knew.
10531 if (offer.neededFor(request)) {
10532 offer.onNetworkUnneeded(request);
10533 }
10534 }
10535 }
10536
Chalard Jean61c79252019-11-07 23:07:32 +090010537 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10538 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10539 NetworkRequest nr = nai.requestAt(i);
10540 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10541 // legacy type tracker filters out repeat adds
10542 mLegacyTypeTracker.add(nr.legacyType, nai);
10543 }
10544 }
10545
10546 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010547 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010548 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10549 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10550 if (nai.isVPN()) {
10551 mLegacyTypeTracker.add(TYPE_VPN, nai);
10552 }
10553 }
10554
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010555 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010556 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010557 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010558 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010559 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010560 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010561
Chalard Jean254bd162022-08-25 13:04:51 +090010562 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010563 // Don't repeat publish.
10564 if (newInetCondition == mDefaultInetConditionPublished) return;
10565
10566 mDefaultInetConditionPublished = newInetCondition;
10567 sendInetConditionBroadcast(nai.networkInfo);
10568 }
10569
Chalard Jeand61375d2020-01-14 22:46:36 +090010570 @NonNull
10571 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10572 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010573 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010574 final boolean suspended =
10575 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10576 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10577 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10578 // state. This is because the network could have been suspended before connecting,
10579 // or it could be disconnecting while being suspended, and in both these cases
10580 // the state should not be overridden. Note that the only detailed state that
10581 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10582 // worry about multiple different substates of CONNECTED.
10583 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10584 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010585 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10586 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10587 // network agent is created, then goes to suspended, then goes out of suspended without
10588 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010589 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010590 ? NetworkInfo.DetailedState.CONNECTED
10591 : NetworkInfo.DetailedState.CONNECTING,
10592 info.getReason(),
10593 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010594 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010595 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010596 return newInfo;
10597 }
10598
10599 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10600 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10601
Erik Kline99f301b2017-02-15 19:59:17 +090010602 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010603 NetworkInfo oldInfo = null;
10604 synchronized (networkAgent) {
10605 oldInfo = networkAgent.networkInfo;
10606 networkAgent.networkInfo = newInfo;
10607 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010608
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010609 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010610 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10611 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010612 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010613
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010614 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010615 // A network that has just connected has zero requests and is thus a foreground network.
10616 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10617
Luke Huangfdd11f82019-04-09 18:41:49 +080010618 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010619
10620 networkAgent.setCreated();
10621
10622 // If the network is created immediately on register, then apply the LinkProperties now.
10623 // Otherwise, this is done further down when the network goes into connected state.
10624 // Applying the LinkProperties means that the network is ready to carry traffic -
10625 // interfaces and routing rules have been added, DNS servers programmed, etc.
10626 // For VPNs, this must be done before the capabilities are updated, because as soon as
10627 // that happens, UIDs are routed to the network.
10628 if (shouldCreateNetworksImmediately()) {
10629 applyInitialLinkProperties(networkAgent);
10630 }
10631
10632 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10633 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010634 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010635 // Initialize the network's capabilities to their starting values according to the
10636 // underlying networks. This ensures that the capabilities are correct before
10637 // anything happens to the network.
10638 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010639 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010640 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010641 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010642 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010643 }
10644
Chalard Jean254bd162022-08-25 13:04:51 +090010645 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10646 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010647
lucaslin45e639b2019-04-03 17:09:28 +080010648 // NetworkCapabilities need to be set before sending the private DNS config to
10649 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010650 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10651
Erik Kline9a62f012018-03-21 07:18:33 -070010652 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010653 if (!shouldCreateNetworksImmediately()) {
10654 applyInitialLinkProperties(networkAgent);
10655 } else {
10656 // The network was created when the agent registered, and the LinkProperties are
10657 // already up-to-date. However, updateLinkProperties also makes some changes only
10658 // when the network connects. Apply those changes here. On T and below these are
10659 // handled by the applyInitialLinkProperties call just above.
10660 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10661 // If something depends on both LinkProperties and connected state, it should be in
10662 // this method as well.
10663 networkAgent.clatd.update();
10664 updateProxy(networkAgent.linkProperties, null);
10665 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010666
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010667 // If a rate limit has been configured and is applicable to this network (network
10668 // provides internet connectivity), apply it. The tc police filter cannot be attached
10669 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010670 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010671 // Note: in case of a system server crash, the NetworkController constructor in netd
10672 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10673 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10674 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10675 mIngressRateLimit);
10676 }
10677
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010678 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10679 // command must be sent after updating LinkProperties to maximize chances of
10680 // NetworkMonitor seeing the correct LinkProperties when starting.
10681 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010682 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010683 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010684 }
Chalard Jeand4900722022-02-06 12:25:38 +090010685 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10686 params.networkAgentConfig = networkAgent.networkAgentConfig;
10687 params.networkCapabilities = networkAgent.networkCapabilities;
10688 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10689 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010690 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10691 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10692 // call that would cause a Log.wtf to be emitted from the system_server process, and
10693 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10694 // process to check the interface version, just use an SDK check. NetworkStack will
10695 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010696 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010697 networkAgent.networkMonitor().notifyNetworkConnected(params);
10698 } else {
10699 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10700 params.networkCapabilities);
10701 }
Chalard Jean0f141332023-06-05 19:26:17 +090010702 final long evaluationDelay;
10703 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10704 // If the network is anything other than pure wifi, use the default timeout.
10705 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10706 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10707 // If the network is explicitly selected, use the default timeout because it's
10708 // shorter and the user is likely staring at the screen expecting it to validate
10709 // right away.
10710 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10711 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10712 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10713 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10714 } else {
10715 // It's wifi, automatically connected, and bad wifi is preferred : use the
10716 // longer timeout to avoid the device switching to captive portals with bad
10717 // signal or very slow response.
10718 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10719 }
10720 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010721
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010722 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10723 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10724 // capabilities, so it only needs to be done once on initial connect, not every time the
10725 // network's capabilities change. Note that we do this before rematching the network,
10726 // so we could decide to tear it down immediately afterwards. That's fine though - on
10727 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10728 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010729 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010730
junyulai0ac374f2020-12-14 18:41:52 +080010731 // Before first rematching networks, put an inactivity timer without any request, this
10732 // allows {@code updateInactivityState} to update the state accordingly and prevent
10733 // tearing down for any {@code unneeded} evaluation in this period.
10734 // Note that the timer will not be rescheduled since the expiry time is
10735 // fixed after connection regardless of the network satisfying other requests or not.
10736 // But it will be removed as soon as the network satisfies a request for the first time.
10737 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10738 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010739 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010740
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010741 if (mTrackMultiNetworkActivities) {
10742 // Start tracking activity of this network.
10743 // This must be called before rematchAllNetworksAndRequests since the network
10744 // should be tracked when the network becomes the default network.
10745 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10746 // can be triggered later if this network becomes the default network.
10747 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10748 }
10749
Paul Jensen05e85ee2014-09-11 11:00:39 -040010750 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010751 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010752
10753 // This has to happen after matching the requests, because callbacks are just requests.
10754 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010755 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010756 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010757 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010758 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010759 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010760 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010761 if (networkAgent.isVPN()) {
10762 // As the active or bound network changes for apps, broadcast the default proxy, as
10763 // apps may need to update their proxy data. This is called after disconnecting from
10764 // VPN to make sure we do not broadcast the old proxy data.
10765 // TODO(b/122649188): send the broadcast only to VPN users.
10766 mProxyTracker.sendProxyBroadcast();
10767 }
Chalard Jean254bd162022-08-25 13:04:51 +090010768 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10769 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010770 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010771 }
10772 }
10773
Chalard Jean28018572020-12-21 18:36:52 +090010774 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010775 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10776 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010777 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010778 }
10779
Erik Kline99f301b2017-02-15 19:59:17 +090010780 // Notify only this one new request of the current state. Transfer all the
10781 // current state by calling NetworkCapabilities and LinkProperties callbacks
10782 // so that callers can be guaranteed to have as close to atomicity in state
10783 // transfer as can be supported by this current API.
10784 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010785 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010786 if (nri.mPendingIntent != null) {
10787 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10788 // Attempt no subsequent state pushes where intents are involved.
10789 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010790 }
Erik Kline99f301b2017-02-15 19:59:17 +090010791
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010792 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010793 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010794 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10795 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10796 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010797 }
10798
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010799 // Notify the requests on this NAI that the network is now lingered.
10800 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010801 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010802 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10803 }
10804
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010805 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10806 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10807 return vpnBlocked
10808 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10809 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10810 }
10811
10812 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10813 if (blockedReasons == BLOCKED_REASON_NONE) {
10814 mUidBlockedReasons.delete(uid);
10815 } else {
10816 mUidBlockedReasons.put(uid, blockedReasons);
10817 }
10818 }
10819
junyulaif2c67e42018-08-07 19:50:45 +080010820 /**
10821 * Notify of the blocked state apps with a registered callback matching a given NAI.
10822 *
10823 * Unlike other callbacks, blocked status is different between each individual uid. So for
10824 * any given nai, all requests need to be considered according to the uid who filed it.
10825 *
10826 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010827 * @param oldMetered True if the previous network capabilities were metered.
10828 * @param newMetered True if the current network capabilities are metered.
10829 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10830 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010831 */
10832 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010833 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10834 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010835
10836 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10837 NetworkRequest nr = nai.requestAt(i);
10838 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010839
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010840 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10841 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10842 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010843 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010844 : oldVpnBlocked;
10845
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010846 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10847 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10848 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010849 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010850 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010851 }
10852 }
10853 }
10854
10855 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010856 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010857 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010858 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010859 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010860 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010861 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010862 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010863 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010864
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010865 final int oldBlockedState = getBlockedState(
10866 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10867 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10868 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010869 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010870 }
junyulaif2c67e42018-08-07 19:50:45 +080010871 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10872 NetworkRequest nr = nai.requestAt(i);
10873 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010874 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010875 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10876 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010877 }
10878 }
10879 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010880 }
10881
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010882 @VisibleForTesting
10883 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010884 // The NetworkInfo we actually send out has no bearing on the real
10885 // state of affairs. For example, if the default connection is mobile,
10886 // and a request for HIPRI has just gone away, we need to pretend that
10887 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10888 // the state to DISCONNECTED, even though the network is of type MOBILE
10889 // and is still connected.
10890 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10891 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010892 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010893 if (state != DetailedState.DISCONNECTED) {
10894 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010895 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010896 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010897 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010898 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10899 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10900 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10901 if (info.isFailover()) {
10902 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10903 nai.networkInfo.setFailover(false);
10904 }
10905 if (info.getReason() != null) {
10906 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10907 }
10908 if (info.getExtraInfo() != null) {
10909 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10910 }
10911 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010912 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010913 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010914 if (newDefaultAgent != null) {
10915 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10916 newDefaultAgent.networkInfo);
10917 } else {
10918 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10919 }
10920 }
10921 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10922 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010923 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010924 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010925 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010926 }
10927 }
10928 }
10929
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010930 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010931 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010932 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010933 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010934 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010935 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10936 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010937 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10938 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010939 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010940 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010941 } else {
10942 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10943 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010944 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010945 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010946
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010947 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10948 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10949 }
10950
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010951 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010952 * Returns the list of all interfaces that could be used by network traffic that does not
10953 * explicitly specify a network. This includes the default network, but also all VPNs that are
10954 * currently connected.
10955 *
10956 * Must be called on the handler thread.
10957 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010958 @NonNull
10959 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010960 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010961 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010962 final Set<Integer> activeNetIds = new ArraySet<>();
10963 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10964 if (nri.isBeingSatisfied()) {
10965 activeNetIds.add(nri.getSatisfier().network().netId);
10966 }
10967 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010968 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010969 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010970 defaultNetworks.add(nai.network);
10971 }
10972 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010973 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010974 }
10975
10976 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010977 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10978 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010979 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010980 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010981 ensureRunningOnConnectivityServiceThread();
10982 String activeIface = null;
10983 LinkProperties activeLinkProperties = getActiveLinkProperties();
10984 if (activeLinkProperties != null) {
10985 activeIface = activeLinkProperties.getInterfaceName();
10986 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010987
junyulai2050bed2021-01-23 09:46:34 +080010988 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010989 try {
junyulaide41fc22021-01-22 22:46:01 +080010990 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010991 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010992 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10993 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010994 } catch (Exception ignored) {
10995 }
10996 }
10997
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010998 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010999 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080011000 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090011001 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090011002 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011003
11004 if (!TextUtils.isEmpty(settingUrl)) {
11005 return settingUrl;
11006 }
11007
11008 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011009 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011010 if (!TextUtils.isEmpty(settingUrl)) {
11011 return settingUrl;
11012 }
11013
11014 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080011015 }
11016
11017 @Override
junyulai070f9ff2019-01-16 20:23:34 +080011018 public void startNattKeepalive(Network network, int intervalSeconds,
11019 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011020 enforceKeepalivePermission();
11021 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080011022 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000011023 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
11024 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000011025 // false and set the underpinned network to null because there is no way and no
11026 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
11027 // deprecated method.
11028 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011029 }
11030
11031 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011032 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080011033 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000011034 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070011035 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080011036 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011037 mKeepaliveTracker.startNattKeepalive(
11038 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000011039 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
11040 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070011041 } finally {
11042 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11043 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011044 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11045 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011046 }
11047 }
junyulaid05a1922019-01-15 11:32:44 +080011048 }
11049
11050 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011051 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080011052 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070011053 try {
11054 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080011055 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011056 mKeepaliveTracker.startTcpKeepalive(
11057 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
11058 } finally {
11059 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11060 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011061 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11062 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011063 }
11064 }
junyulai0835a1e2019-01-08 20:04:33 +080011065 }
11066
11067 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011068 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011069 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011070 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
11071 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011072 }
11073
11074 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090011075 public int[] getSupportedKeepalives() {
11076 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
11077 // Backwards compatibility with CTS 13
11078 android.Manifest.permission.QUERY_ALL_PACKAGES);
11079
11080 return BinderUtils.withCleanCallingIdentity(() ->
11081 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
11082 }
11083
11084 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070011085 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080011086 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070011087
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011088 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080011089 final long token = Binder.clearCallingIdentity();
11090 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011091 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
11092 UserHandle.getUserHandleForUid(uid))) {
11093 return;
11094 }
11095
Heemin Seogdb8489d2019-06-12 09:21:44 -070011096 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
11097 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011098
11099 // Turn airplane mode off
11100 setAirplaneMode(false);
11101
11102 // restore private DNS settings to default mode (opportunistic)
11103 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
11104 UserHandle.getUserHandleForUid(uid))) {
11105 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
11106 PRIVATE_DNS_MODE_OPPORTUNISTIC);
11107 }
11108
11109 Settings.Global.putString(mContext.getContentResolver(),
11110 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080011111 } finally {
11112 Binder.restoreCallingIdentity(token);
11113 }
Stuart Scottd5463642015-04-02 18:00:02 -070011114 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040011115
Ricky Wai7097cc92018-01-23 04:09:45 +000011116 @Override
11117 public byte[] getNetworkWatchlistConfigHash() {
11118 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
11119 if (nwm == null) {
11120 loge("Unable to get NetworkWatchlistManager");
11121 return null;
11122 }
11123 // Redirect it to network watchlist service to access watchlist file and calculate hash.
11124 return nwm.getWatchlistConfigHash();
11125 }
11126
Hugo Benichibe0c7652016-05-31 16:28:06 +090011127 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090011128 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080011129 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090011130 }
Hugo Benichif4210292017-04-21 15:07:12 +090011131
11132 private static boolean toBool(int encodedBoolean) {
11133 return encodedBoolean != 0; // Only 0 means false.
11134 }
11135
11136 private static int encodeBool(boolean b) {
11137 return b ? 1 : 0;
11138 }
mswest4632928412018-03-12 10:34:34 -070011139
11140 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011141 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
11142 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
11143 @NonNull String[] args) {
11144 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11145 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011146 }
11147
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011148 private Boolean parseBooleanArgument(final String arg) {
11149 if ("true".equals(arg)) {
11150 return true;
11151 } else if ("false".equals(arg)) {
11152 return false;
11153 } else {
11154 return null;
11155 }
11156 }
11157
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011158 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070011159 @Override
11160 public int onCommand(String cmd) {
11161 if (cmd == null) {
11162 return handleDefaultCommands(cmd);
11163 }
11164 final PrintWriter pw = getOutPrintWriter();
11165 try {
11166 switch (cmd) {
11167 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011168 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11169 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011170 final String action = getNextArg();
11171 if ("enable".equals(action)) {
11172 setAirplaneMode(true);
11173 return 0;
11174 } else if ("disable".equals(action)) {
11175 setAirplaneMode(false);
11176 return 0;
11177 } else if (action == null) {
11178 final ContentResolver cr = mContext.getContentResolver();
11179 final int enabled = Settings.Global.getInt(cr,
11180 Settings.Global.AIRPLANE_MODE_ON);
11181 pw.println(enabled == 0 ? "disabled" : "enabled");
11182 return 0;
11183 } else {
11184 onHelp();
11185 return -1;
11186 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011187 case "set-chain3-enabled": {
11188 final Boolean enabled = parseBooleanArgument(getNextArg());
11189 if (null == enabled) {
11190 onHelp();
11191 return -1;
11192 }
11193 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11194 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11195 enabled);
11196 return 0;
11197 }
11198 case "get-chain3-enabled": {
11199 final boolean chainEnabled = getFirewallChainEnabled(
11200 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11201 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11202 return 0;
11203 }
11204 case "set-package-networking-enabled": {
11205 final Boolean enabled = parseBooleanArgument(getNextArg());
11206 final String packageName = getNextArg();
11207 if (null == enabled || null == packageName) {
11208 onHelp();
11209 return -1;
11210 }
11211 // Throws NameNotFound if the package doesn't exist.
11212 final int appId = setPackageFirewallRule(
11213 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11214 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11215 final String msg = (enabled ? "Enabled" : "Disabled")
11216 + " networking for " + packageName + ", appId " + appId;
11217 Log.i(TAG, msg);
11218 pw.println(msg);
11219 return 0;
11220 }
11221 case "get-package-networking-enabled": {
11222 final String packageName = getNextArg();
11223 final int rule = getPackageFirewallRule(
11224 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11225 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11226 pw.println(packageName + ":" + "allow");
11227 } else if (FIREWALL_RULE_DENY == rule) {
11228 pw.println(packageName + ":" + "deny");
11229 } else {
11230 throw new IllegalStateException("Unknown rule " + rule + " for package "
11231 + packageName);
11232 }
11233 return 0;
11234 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011235 case "reevaluate":
11236 // Usage : adb shell cmd connectivity reevaluate <netId>
11237 // If netId is omitted, then reevaluate the default network
11238 final String netId = getNextArg();
11239 final NetworkAgentInfo nai;
11240 if (null == netId) {
11241 // Note that the command is running on the wrong thread to call this,
11242 // so this could in principle return stale data. But it can't crash.
11243 nai = getDefaultNetwork();
11244 } else {
11245 // If netId can't be parsed, this throws NumberFormatException, which
11246 // is passed back to adb who prints it.
11247 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11248 }
11249 if (null == nai) {
11250 pw.println("Unknown network (net ID not found or no default network)");
11251 return 0;
11252 }
11253 Log.d(TAG, "Reevaluating network " + nai.network);
11254 reportNetworkConnectivity(nai.network, !nai.isValidated());
11255 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011256 case "bpf-get-cgroup-program-id": {
11257 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11258 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11259 // for more detail.
11260 // If type can't be parsed, this throws NumberFormatException, which
11261 // is passed back to adb who prints it.
11262 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011263 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011264 pw.println(ret);
11265 return 0;
11266 }
mswest4632928412018-03-12 10:34:34 -070011267 default:
11268 return handleDefaultCommands(cmd);
11269 }
11270 } catch (Exception e) {
11271 pw.println(e);
11272 }
11273 return -1;
11274 }
11275
11276 @Override
11277 public void onHelp() {
11278 PrintWriter pw = getOutPrintWriter();
11279 pw.println("Connectivity service commands:");
11280 pw.println(" help");
11281 pw.println(" Print this help text.");
11282 pw.println(" airplane-mode [enable|disable]");
11283 pw.println(" Turn airplane mode on or off.");
11284 pw.println(" airplane-mode");
11285 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011286 pw.println(" set-chain3-enabled [true|false]");
11287 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11288 pw.println(" get-chain3-enabled");
11289 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11290 pw.println(" set-package-networking-enabled [true|false] [package name]");
11291 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11292 + " no effect if the chain is disabled.");
11293 pw.println(" get-package-networking-enabled [package name]");
11294 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011295 }
11296 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011297
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011298 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011299 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11300 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11301 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011302 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011303 }
11304
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011305 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11306 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011307 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11308 final TransportInfo newInfo = nc.getTransportInfo();
11309 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11310 return;
11311 }
11312 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011313 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011314 }
11315 }
11316
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011317 /**
11318 * @param connectionInfo the connection to resolve.
11319 * @return {@code uid} if the connection is found and the app has permission to observe it
11320 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11321 * connection is not found.
11322 */
11323 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011324 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11325 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11326 }
11327
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011328 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011329 connectionInfo.local, connectionInfo.remote);
11330
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011331 if (uid == INVALID_UID) return uid; // Not found.
11332
11333 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11334 // VPN, if any, that applies to the UID that owns the connection.
Junyu Lai71b51532024-02-01 10:39:01 +080011335 if (hasNetworkStackPermission()) return uid;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011336
11337 final NetworkAgentInfo vpn = getVpnForUid(uid);
11338 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011339 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011340 return INVALID_UID;
11341 }
11342
11343 return uid;
11344 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011345
Benedict Wong493e04b2018-11-09 14:45:34 -080011346 /**
11347 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11348 *
11349 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11350 */
11351 @Override
11352 public IBinder startOrGetTestNetworkService() {
11353 synchronized (mTNSLock) {
11354 TestNetworkService.enforceTestNetworkPermissions(mContext);
11355
11356 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011357 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011358 }
11359
11360 return mTNS;
11361 }
11362 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011363
Cody Kesting73708bf2019-12-18 10:57:50 -080011364 /**
11365 * Handler used for managing all Connectivity Diagnostics related functions.
11366 *
11367 * @see android.net.ConnectivityDiagnosticsManager
11368 *
11369 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11370 */
11371 @VisibleForTesting
11372 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011373 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11374
Cody Kesting73708bf2019-12-18 10:57:50 -080011375 /**
11376 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11377 * android.net.ConnectivityDiagnosticsManager}.
11378 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11379 * NetworkRequestInfo to be registered
11380 */
11381 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11382
11383 /**
11384 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11385 * android.net.ConnectivityDiagnosticsManager}.
11386 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11387 * arg1 = the uid of the caller
11388 */
11389 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11390
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011391 /**
11392 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011393 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011394 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11395 * NetworkMonitor.
11396 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011397 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011398 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011399
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011400 /**
11401 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11402 * been detected on the network.
11403 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11404 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11405 * arg2 = NetID.
11406 * data = PersistableBundle of extras passed from NetworkMonitor.
11407 */
11408 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11409
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011410 /**
11411 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11412 * the platform. This event will invoke {@link
11413 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11414 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011415 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011416 */
11417 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11418
Cody Kesting73708bf2019-12-18 10:57:50 -080011419 private ConnectivityDiagnosticsHandler(Looper looper) {
11420 super(looper);
11421 }
11422
11423 @Override
11424 public void handleMessage(Message msg) {
11425 switch (msg.what) {
11426 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11427 handleRegisterConnectivityDiagnosticsCallback(
11428 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11429 break;
11430 }
11431 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11432 handleUnregisterConnectivityDiagnosticsCallback(
11433 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11434 break;
11435 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011436 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011437 final ConnectivityReportEvent reportEvent =
11438 (ConnectivityReportEvent) msg.obj;
11439
Aaron Huang959d3642021-01-21 15:47:41 +080011440 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011441 break;
11442 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011443 case EVENT_DATA_STALL_SUSPECTED: {
11444 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011445 final Pair<Long, PersistableBundle> arg =
11446 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011447 if (nai == null) break;
11448
Aaron Huang959d3642021-01-21 15:47:41 +080011449 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011450 break;
11451 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011452 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011453 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011454 break;
11455 }
11456 default: {
11457 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11458 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011459 }
11460 }
11461 }
11462
11463 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11464 @VisibleForTesting
11465 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11466 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11467 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011468 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011469
11470 @VisibleForTesting
11471 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011472 @NonNull IConnectivityDiagnosticsCallback cb,
11473 @NonNull NetworkRequestInfo nri,
11474 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011475 mCb = cb;
11476 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011477 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011478 }
11479
11480 @Override
11481 public void binderDied() {
11482 log("ConnectivityDiagnosticsCallback IBinder died.");
11483 unregisterConnectivityDiagnosticsCallback(mCb);
11484 }
11485 }
11486
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011487 /**
11488 * Class used for sending information from {@link
11489 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11490 */
11491 private static class NetworkTestedResults {
11492 private final int mNetId;
11493 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011494 @Nullable private final String mRedirectUrl;
11495
11496 private NetworkTestedResults(
11497 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11498 mNetId = netId;
11499 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011500 mRedirectUrl = redirectUrl;
11501 }
11502 }
11503
11504 /**
11505 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11506 * ConnectivityDiagnosticsHandler}.
11507 */
11508 private static class ConnectivityReportEvent {
11509 private final long mTimestampMillis;
11510 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011511 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011512
Aaron Huang959d3642021-01-21 15:47:41 +080011513 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11514 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011515 mTimestampMillis = timestampMillis;
11516 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011517 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011518 }
11519 }
11520
Cody Kestingf1120be2020-08-03 18:01:40 -070011521 /**
11522 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11523 * ConnectivityDiagnosticsHandler}.
11524 */
11525 private static class ReportedNetworkConnectivityInfo {
11526 public final boolean hasConnectivity;
11527 public final boolean isNetworkRevalidating;
11528 public final int reporterUid;
11529 @NonNull public final NetworkAgentInfo nai;
11530
11531 private ReportedNetworkConnectivityInfo(
11532 boolean hasConnectivity,
11533 boolean isNetworkRevalidating,
11534 int reporterUid,
11535 @NonNull NetworkAgentInfo nai) {
11536 this.hasConnectivity = hasConnectivity;
11537 this.isNetworkRevalidating = isNetworkRevalidating;
11538 this.reporterUid = reporterUid;
11539 this.nai = nai;
11540 }
11541 }
11542
Cody Kesting73708bf2019-12-18 10:57:50 -080011543 private void handleRegisterConnectivityDiagnosticsCallback(
11544 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11545 ensureRunningOnConnectivityServiceThread();
11546
11547 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011548 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011549 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11550
James Mattis64b8b0f2020-11-24 17:40:49 -080011551 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11552 // confusing for these networks to change when an NRI is satisfied in another layer.
11553 if (nri.isMultilayerRequest()) {
11554 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11555 + "network requests.");
11556 }
11557
Cody Kesting73708bf2019-12-18 10:57:50 -080011558 // This means that the client registered the same callback multiple times. Do
11559 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011560 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011561 if (VDBG) log("Diagnostics callback is already registered");
11562
11563 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11564 // incremented when the NetworkRequestInfo is created as part of
11565 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011566 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011567 return;
11568 }
11569
Cody Kesting31f1ff62020-03-05 10:46:02 -080011570 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011571
11572 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011573 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011574 } catch (RemoteException e) {
11575 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011576 return;
11577 }
11578
11579 // Once registered, provide ConnectivityReports for matching Networks
11580 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11581 synchronized (mNetworkForNetId) {
11582 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11583 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011584 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11585 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011586 matchingNetworks.add(nai);
11587 }
11588 }
11589 }
11590 for (final NetworkAgentInfo nai : matchingNetworks) {
11591 final ConnectivityReport report = nai.getConnectivityReport();
11592 if (report == null) {
11593 continue;
11594 }
Junyu Lai71b51532024-02-01 10:39:01 +080011595 if (!hasConnectivityDiagnosticsPermissions(
Cody Kestingb77bf702020-02-12 14:50:58 -080011596 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11597 continue;
11598 }
11599
11600 try {
11601 cb.onConnectivityReportAvailable(report);
11602 } catch (RemoteException e) {
11603 // Exception while sending the ConnectivityReport. Move on to the next network.
11604 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011605 }
11606 }
11607
11608 private void handleUnregisterConnectivityDiagnosticsCallback(
11609 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11610 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011611 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011612
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011613 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11614 mConnectivityDiagnosticsCallbacks.remove(iCb);
11615 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011616 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11617 return;
11618 }
11619
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011620 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011621
Cody Kesting70fa2b22020-12-02 12:16:56 -080011622 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11623 // (if the Binder died)
11624 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11625 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011626 return;
11627 }
11628
Cody Kesting46cb1672020-03-04 13:35:20 -080011629 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11630 // incremented when the NetworkRequestInfo is created as part of
11631 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011632 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011633
Cody Kesting31f1ff62020-03-05 10:46:02 -080011634 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011635 }
11636
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011637 private void handleNetworkTestedWithExtras(
11638 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11639 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011640 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011641 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011642 final ConnectivityReport report =
11643 new ConnectivityReport(
11644 reportEvent.mNai.network,
11645 reportEvent.mTimestampMillis,
11646 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011647 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011648 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011649 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011650
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011651 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011652 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011653 for (final IConnectivityDiagnosticsCallback cb : results) {
11654 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011655 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011656 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011657 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011658 }
11659 }
11660 }
11661
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011662 private void handleDataStallSuspected(
11663 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11664 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011665 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011666 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011667 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011668 new DataStallReport(
11669 nai.network,
11670 timestampMillis,
11671 detectionMethod,
11672 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011673 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011674 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011675 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011676 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011677 for (final IConnectivityDiagnosticsCallback cb : results) {
11678 try {
11679 cb.onDataStallSuspected(report);
11680 } catch (RemoteException ex) {
11681 loge("Error invoking onDataStallSuspected", ex);
11682 }
11683 }
11684 }
11685
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011686 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011687 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11688 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11689 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11690
11691 // If the Network is being re-validated as a result of this call to
11692 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11693 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011694 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011695 getMatchingPermissionedCallbacks(
11696 nai,
11697 reportedNetworkConnectivityInfo.isNetworkRevalidating
11698 ? Process.INVALID_UID
11699 : reportedNetworkConnectivityInfo.reporterUid);
11700
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011701 for (final IConnectivityDiagnosticsCallback cb : results) {
11702 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011703 cb.onNetworkConnectivityReported(
11704 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011705 } catch (RemoteException ex) {
11706 loge("Error invoking onNetworkConnectivityReported", ex);
11707 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011708
11709 // If the Network isn't re-validating, also provide the cached report. If there is no
11710 // cached report, the Network is still being validated and a report will be sent once
11711 // validation is complete. Note that networks which never undergo validation will still
11712 // have a cached ConnectivityReport with RESULT_SKIPPED.
11713 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11714 try {
11715 cb.onConnectivityReportAvailable(cachedReport);
11716 } catch (RemoteException ex) {
11717 loge("Error invoking onConnectivityReportAvailable", ex);
11718 }
11719 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011720 }
11721 }
11722
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011723 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011724 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11725 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011726 sanitized.setUids(null);
11727 sanitized.setAdministratorUids(new int[0]);
11728 sanitized.setOwnerUid(Process.INVALID_UID);
11729 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011730 }
11731
Cody Kestingf1120be2020-08-03 18:01:40 -070011732 /**
11733 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11734 *
11735 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11736 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011737 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011738 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011739 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011740 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011741 mConnectivityDiagnosticsCallbacks.entrySet()) {
11742 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11743 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011744
James Mattis64b8b0f2020-11-24 17:40:49 -080011745 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011746 if (!nai.satisfies(nri.mRequests.get(0))) {
11747 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011748 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011749
11750 // UID for this callback must either be:
11751 // - INVALID_UID (which sends callbacks to all UIDs), or
11752 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11753 // notified as a result)
11754 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11755 continue;
11756 }
11757
Junyu Lai71b51532024-02-01 10:39:01 +080011758 if (!hasConnectivityDiagnosticsPermissions(
Cody Kestingf1120be2020-08-03 18:01:40 -070011759 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11760 continue;
11761 }
11762
11763 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011764 }
11765 return results;
11766 }
11767
Cody Kesting7474f672021-05-11 14:22:40 -070011768 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11769 @NonNull NetworkAgentInfo nai) {
11770 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11771 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11772 }
11773
Cody Kesting160ef392021-05-05 13:17:22 -070011774 private boolean hasLocationPermission(String packageName, int uid) {
11775 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11776 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11777 // call in a try-catch.
11778 try {
11779 if (!mLocationPermissionChecker.checkLocationPermission(
11780 packageName, null /* featureId */, uid, null /* message */)) {
11781 return false;
11782 }
11783 } catch (SecurityException e) {
11784 return false;
11785 }
11786
11787 return true;
11788 }
11789
11790 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11791 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011792 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011793 && virtual.networkCapabilities.getOwnerUid() == uid
11794 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11795 return true;
11796 }
11797 }
11798
11799 return false;
11800 }
11801
Junyu Lai71b51532024-02-01 10:39:01 +080011802 @CheckResult
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011803 @VisibleForTesting
Junyu Lai71b51532024-02-01 10:39:01 +080011804 boolean hasConnectivityDiagnosticsPermissions(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011805 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
Junyu Lai71b51532024-02-01 10:39:01 +080011806 if (hasNetworkStackPermission(callbackPid, callbackUid)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011807 return true;
11808 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011809 if (mAllowSysUiConnectivityReports
Junyu Lai71b51532024-02-01 10:39:01 +080011810 && hasSystemBarServicePermission(callbackPid, callbackUid)) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011811 return true;
11812 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011813
Cody Kesting160ef392021-05-05 13:17:22 -070011814 // Administrator UIDs also contains the Owner UID
11815 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11816 if (!CollectionUtils.contains(administratorUids, callbackUid)
11817 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011818 return false;
11819 }
11820
Cody Kesting7474f672021-05-11 14:22:40 -070011821 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11822 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011823 }
11824
Cody Kestingd199a9d2019-12-17 12:55:28 -080011825 @Override
11826 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011827 @NonNull IConnectivityDiagnosticsCallback callback,
11828 @NonNull NetworkRequest request,
11829 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011830 Objects.requireNonNull(callback, "callback must not be null");
11831 Objects.requireNonNull(request, "request must not be null");
11832 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11833
Cody Kesting73708bf2019-12-18 10:57:50 -080011834 if (request.legacyType != TYPE_NONE) {
11835 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11836 + " Please use NetworkCapabilities instead.");
11837 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011838 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011839 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011840
11841 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11842 // and administrator uids to be safe.
11843 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011844 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011845
11846 final NetworkRequest requestWithId =
11847 new NetworkRequest(
11848 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11849
11850 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11851 //
11852 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11853 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11854 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011855 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011856 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011857 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011858
11859 mConnectivityDiagnosticsHandler.sendMessage(
11860 mConnectivityDiagnosticsHandler.obtainMessage(
11861 ConnectivityDiagnosticsHandler
11862 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11863 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011864 }
11865
11866 @Override
11867 public void unregisterConnectivityDiagnosticsCallback(
11868 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011869 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011870 mConnectivityDiagnosticsHandler.sendMessage(
11871 mConnectivityDiagnosticsHandler.obtainMessage(
11872 ConnectivityDiagnosticsHandler
11873 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011874 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011875 0,
11876 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011877 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011878
Yan Yanfe96dde2022-12-05 23:00:01 +000011879 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11880 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11881 if (underlyingNetworks == null) return false;
11882
11883 for (Network network : underlyingNetworks) {
11884 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11885 return true;
11886 }
11887 }
11888 return false;
11889 }
11890
Cody Kestingf53a0752020-04-15 12:33:28 -070011891 @Override
11892 public void simulateDataStall(int detectionMethod, long timestampMillis,
11893 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011894 Objects.requireNonNull(network, "network must not be null");
11895 Objects.requireNonNull(extras, "extras must not be null");
11896
paulhu3ffffe72021-09-16 10:15:22 +080011897 enforceAnyPermissionOf(mContext,
11898 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011899 android.Manifest.permission.NETWORK_STACK);
11900 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011901 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11902 throw new SecurityException(
11903 "Data Stall simulation is only possible for test networks or networks built on"
11904 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011905 }
11906
11907 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011908 if (nai == null
11909 || (nai.creatorUid != mDeps.getCallingUid()
11910 && nai.creatorUid != Process.SYSTEM_UID)) {
11911 throw new SecurityException(
11912 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011913 }
11914
Cody Kesting652e3ec2020-05-21 12:08:21 -070011915 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11916 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11917 // Data Stall information as a DataStallReportParcelable and passing to
11918 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11919 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011920 final DataStallReportParcelable p = new DataStallReportParcelable();
11921 p.timestampMillis = timestampMillis;
11922 p.detectionMethod = detectionMethod;
11923
11924 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11925 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11926 }
11927 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11928 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11929 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11930 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11931 }
11932
Serik Beketayevec8ad212020-12-07 22:43:07 -080011933 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011934 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011935
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011936 /**
11937 * Class to hold the information for network activity change event from idle timers
11938 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11939 */
11940 private static final class NetworkActivityParams {
11941 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011942 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
11943 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011944 public final int label;
11945 public final long timestampNs;
11946 // Uid represents the uid that was responsible for waking the radio.
11947 // -1 for no uid and uid is -1 if isActive is false.
11948 public final int uid;
11949
11950 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11951 this.isActive = isActive;
11952 this.label = label;
11953 this.timestampNs = timestampNs;
11954 this.uid = uid;
11955 }
11956 }
11957
lucaslin66f44212021-02-23 01:12:55 +080011958 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11959 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011960 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011961 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011962 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11963 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011964 }
lucaslin37a16d92021-01-21 19:48:09 +080011965
11966 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011967 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011968 mHandler.post(() -> {
11969 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011970 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011971 }
11972 });
lucaslin37a16d92021-01-21 19:48:09 +080011973 }
11974
11975 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011976 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011977 mHandler.post(() -> {
11978 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011979 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011980 }
11981 });
lucaslin66f44212021-02-23 01:12:55 +080011982 }
11983 }
11984
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011985 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080011986 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11987
11988 /**
11989 * Class used for updating network activity tracking with netd and notify network activity
11990 * changes.
11991 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011992 @VisibleForTesting
11993 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011994 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011995 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011996 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011997 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011998 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11999 new RemoteCallbackList<>();
12000 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012001 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012002 // If there is no default network, default network is considered active to keep the existing
12003 // behavior. Initial value is used until first connect to the default network.
12004 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012005 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012006 // Key is netId. Value is configured idle timer information.
12007 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012008 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012009 // Store netIds of Wi-Fi networks whose idletimers report that they are active
12010 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
12011 // Store netIds of cellular networks whose idletimers report that they are active
12012 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080012013
Chalard Jean46bfbf02022-02-02 00:56:25 +090012014 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080012015 public final int timeout;
12016 public final int transportType;
12017
12018 IdleTimerParams(int timeout, int transport) {
12019 this.timeout = timeout;
12020 this.transportType = transport;
12021 }
12022 }
12023
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012024 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012025 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012026 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080012027 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012028 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012029 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012030 }
12031
12032 private void ensureRunningOnConnectivityServiceThread() {
12033 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
12034 throw new IllegalStateException("Not running on ConnectivityService thread: "
12035 + Thread.currentThread().getName());
12036 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012037 }
12038
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012039 /**
12040 * Update network activity and call BatteryStats to update radio power state if the
12041 * mobile or Wi-Fi activity is changed.
12042 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
12043 * mobile network is active since BatteryStatsService only maintains a single power state
12044 * for the mobile network.
12045 * The Wi-Fi network is also the same.
12046 *
12047 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
12048 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
12049 * transports.
12050 */
12051 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
12052 final boolean isActive, final int uid) {
12053 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
12054 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
12055 + transportType);
12056 return;
12057 }
12058 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
12059 ? mActiveWifiNetworks : mActiveCellularNetworks;
12060
12061 final boolean wasEmpty = activeNetworks.isEmpty();
12062 if (isActive) {
12063 activeNetworks.add(netId);
12064 } else {
12065 activeNetworks.remove(netId);
12066 }
12067
12068 if (wasEmpty != activeNetworks.isEmpty()) {
12069 updateRadioPowerState(isActive, transportType, uid);
12070 }
12071 }
12072
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012073 private void handleDefaultNetworkActivity(final int transportType,
12074 final boolean isActive, final long timestampNs) {
12075 mIsDefaultNetworkActive = isActive;
12076 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
12077 isActive, timestampNs);
12078 if (isActive) {
12079 reportNetworkActive();
12080 }
12081 }
12082
12083 private void handleReportNetworkActivityWithNetIdLabel(
12084 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012085 final int netId = activityParams.label;
12086 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012087 if (idleTimerParams == null) {
12088 // This network activity change is not tracked anymore
12089 // This can happen if netd callback post activity change event message but idle
12090 // timer is removed before processing this message.
12091 return;
12092 }
12093 // TODO: if a network changes transports, storing the transport type in the
12094 // IdleTimerParams is not correct. Consider getting it from the network's
12095 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012096 final int transportType = idleTimerParams.transportType;
12097 maybeUpdateRadioPowerState(netId, transportType,
12098 activityParams.isActive, activityParams.uid);
12099
12100 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
12101 // This activity change is not for the default network.
12102 return;
12103 }
12104
12105 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012106 activityParams.timestampNs);
12107 }
12108
12109 private void handleReportNetworkActivityWithTransportTypeLabel(
12110 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012111 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012112 // This activity change is not for the current default network.
12113 // This can happen if netd callback post activity change event message but
12114 // the default network is lost before processing this message.
12115 return;
12116 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012117 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
12118 activityParams.timestampNs);
12119 }
12120
12121 /**
12122 * Handle network activity change
12123 */
12124 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
12125 ensureRunningOnConnectivityServiceThread();
12126 if (mTrackMultiNetworkActivities) {
12127 handleReportNetworkActivityWithNetIdLabel(activityParams);
12128 } else {
12129 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080012130 }
12131 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012132
lucaslin1193a5d2021-01-21 02:04:15 +080012133 private void reportNetworkActive() {
12134 final int length = mNetworkActivityListeners.beginBroadcast();
12135 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
12136 try {
12137 for (int i = 0; i < length; i++) {
12138 try {
12139 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
12140 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012141 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080012142 }
12143 }
12144 } finally {
12145 mNetworkActivityListeners.finishBroadcast();
12146 }
12147 }
12148
lucaslin1a8b4c62021-01-21 02:02:55 +080012149 // This is deprecated and only to support legacy use cases.
12150 private int transportTypeToLegacyType(int type) {
12151 switch (type) {
12152 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012153 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012154 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012155 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012156 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012157 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012158 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012159 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012160 default:
12161 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12162 }
12163 return ConnectivityManager.TYPE_NONE;
12164 }
12165
12166 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12167 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12168 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12169 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12170 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12171 final long ident = Binder.clearCallingIdentity();
12172 try {
12173 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12174 RECEIVE_DATA_ACTIVITY_CHANGE,
12175 null /* resultReceiver */,
12176 null /* scheduler */,
12177 0 /* initialCode */,
12178 null /* initialData */,
12179 null /* initialExtra */);
12180 } finally {
12181 Binder.restoreCallingIdentity(ident);
12182 }
12183 }
12184
12185 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012186 * Get idle timer label
12187 */
12188 @VisibleForTesting
12189 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12190 final int netId, final int transportType) {
12191 return trackMultiNetworkActivities ? netId : transportType;
12192 }
12193
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012194 private boolean maybeCreateIdleTimer(
12195 String iface, int netId, int timeout, int transportType) {
12196 if (timeout <= 0 || iface == null) return false;
12197 try {
12198 final String label = Integer.toString(getIdleTimerLabel(
12199 mTrackMultiNetworkActivities, netId, transportType));
12200 mNetd.idletimerAddInterface(iface, timeout, label);
12201 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12202 return true;
12203 } catch (Exception e) {
12204 loge("Exception in createIdleTimer", e);
12205 return false;
12206 }
12207 }
12208
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012209 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012210 * Setup data activity tracking for the given network.
12211 *
12212 * Every {@code setupDataActivityTracking} should be paired with a
12213 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012214 *
12215 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012216 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012217 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012218 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012219 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012220 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012221
12222 final int timeout;
12223 final int type;
12224
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012225 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12226 // Do not track VPN network.
12227 return false;
12228 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012229 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12230 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012231 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012232 10);
12233 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12234 } else if (networkAgent.networkCapabilities.hasTransport(
12235 NetworkCapabilities.TRANSPORT_WIFI)) {
12236 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012237 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012238 15);
12239 type = NetworkCapabilities.TRANSPORT_WIFI;
12240 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012241 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012242 }
12243
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012244 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12245 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12246 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12247 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12248 // state only about a network that has an idletimer.
12249 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012250 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012251 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012252 }
12253
12254 /**
12255 * Remove data activity tracking when network disconnects.
12256 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012257 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12258 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012259 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012260 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012261 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12262
lucaslinb961efc2021-01-21 02:03:17 +080012263 if (iface == null) return;
12264
12265 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012266 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12267 // Do not track VPN network.
12268 return;
12269 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012270 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12271 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12272 type = NetworkCapabilities.TRANSPORT_WIFI;
12273 } else {
12274 return; // do not track any other networks
12275 }
12276
12277 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012278 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012279 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012280 if (params == null) {
12281 // IdleTimer is not added if the configured timeout is 0 or negative value
12282 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012283 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012284 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012285 final String label = Integer.toString(getIdleTimerLabel(
12286 mTrackMultiNetworkActivities, netId, params.transportType));
12287 // The call fails silently if no idle timer setup for this interface
12288 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012289 } catch (Exception e) {
12290 // You shall not crash!
12291 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012292 }
12293 }
12294
Motomu Utsumi6225d572023-05-29 15:08:57 +090012295 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12296 boolean hasIdleTimer) {
12297 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012298 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012299 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012300 // If only the default network is tracked, callbacks are called only when the
12301 // network has the idle timer.
12302 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012303 reportNetworkActive();
12304 }
12305 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012306 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012307 // If there is no default network, default network is considered active to keep the
12308 // existing behavior.
12309 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012310 }
12311 }
12312
lucaslin1a8b4c62021-01-21 02:02:55 +080012313 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012314 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012315 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012316 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012317 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012318 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012319 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12320 // first connected and remove when the network is disconnected.
12321 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12322 // becomes the default network and remove when the network becomes no longer the default
12323 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012324 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012325 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012326 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012327 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012328 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012329 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012330 removeDataActivityTracking(oldNetwork);
12331 }
12332 }
lucaslinb961efc2021-01-21 02:03:17 +080012333
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012334 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012335 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12336 switch (transportType) {
12337 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012338 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012339 break;
12340 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012341 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012342 break;
12343 default:
12344 logw("Untracked transport type:" + transportType);
12345 }
12346 }
lucaslin1193a5d2021-01-21 02:04:15 +080012347
12348 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012349 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012350 }
12351
12352 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12353 mNetworkActivityListeners.register(l);
12354 }
12355
12356 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12357 mNetworkActivityListeners.unregister(l);
12358 }
lucaslin012f7a12021-01-21 02:04:35 +080012359
12360 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012361 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012362 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012363 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012364 pw.println("Idle timers:");
12365 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012366 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12367 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12368 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012369 pw.print(" timeout="); pw.print(params.timeout);
12370 pw.print(" type="); pw.println(params.transportType);
12371 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012372 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12373 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012374 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012375 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12376 // be accessed from handler thread, except dump(). As dump() is never called in
12377 // normal usage, it would be needlessly expensive to lock the collection only for
12378 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012379 // So catching the exception and logging.
12380 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012381 }
12382 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012383 }
James Mattis47db0582021-01-01 14:13:35 -080012384
Daniel Brightf9e945b2020-06-15 16:10:01 -070012385 /**
12386 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12387 *
12388 * @param socketInfo the socket information
12389 * @param callback the callback to register
12390 */
12391 @Override
12392 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12393 @NonNull final IQosCallback callback) {
12394 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12395 if (nai == null || nai.networkCapabilities == null) {
12396 try {
12397 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12398 } catch (final RemoteException ex) {
12399 loge("registerQosCallbackInternal: RemoteException", ex);
12400 }
12401 return;
12402 }
12403 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12404 }
12405
12406 /**
12407 * Register a {@link IQosCallback} with base {@link QosFilter}.
12408 *
12409 * @param filter the filter to register
12410 * @param callback the callback to register
12411 * @param nai the agent information related to the filter's network
12412 */
12413 @VisibleForTesting
12414 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12415 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012416 Objects.requireNonNull(filter, "filter must be non-null");
12417 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012418
12419 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012420 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12421 // on this network is unregistered when the app loses permission or b) no QoS
12422 // callbacks are sent for restricted networks unless the app currently has permission
12423 // to access restricted networks.
12424 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012425 }
12426 mQosCallbackTracker.registerCallback(callback, filter, nai);
12427 }
12428
12429 /**
12430 * Unregisters the given callback.
12431 *
12432 * @param callback the callback to unregister
12433 */
12434 @Override
12435 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012436 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012437 mQosCallbackTracker.unregisterCallback(callback);
12438 }
James Mattis47db0582021-01-01 14:13:35 -080012439
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012440 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12441 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12442 // Enterprise device can be fully managed like device owner and such use case
12443 // also should be supported. Calling app check for work profile and fully managed device
12444 // is already done in DevicePolicyManager.
12445 // This check is an extra caution to be sure device is fully managed or not.
12446 final UserManager um = mContext.getSystemService(UserManager.class);
12447 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12448 if (um.isManagedProfile(profile.getIdentifier())) {
12449 return true;
12450 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012451 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012452 return false;
12453 }
12454
James Mattis45d81842021-01-10 14:24:24 -080012455 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012456 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012457 *
12458 * See the documentation for the individual preferences for a description of the supported
12459 * behaviors.
12460 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012461 * @param profile If the device owner is set, any profile is allowed.
12462 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012463 * @param preferences the list of profile network preferences for the
12464 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012465 * @param listener an optional listener to listen for completion of the operation.
12466 */
12467 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012468 public void setProfileNetworkPreferences(
12469 @NonNull final UserHandle profile,
12470 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012471 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012472 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012473 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012474
12475 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012476 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12477 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12478 .build();
12479 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012480 }
12481
paulhu3ffffe72021-09-16 10:15:22 +080012482 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012483 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012484 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012485 }
12486 if (profile.getIdentifier() < 0) {
12487 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12488 + "UserHandle.CURRENT not supported)");
12489 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012490 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12491 throw new IllegalArgumentException("Profile must be a managed profile "
12492 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012493 }
paulhuaa0743d2021-05-26 21:56:03 +080012494
Chalard Jean0606fc82022-12-14 20:34:43 +090012495 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012496 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012497 for (final ProfileNetworkPreference preference : preferences) {
12498 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012499 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012500 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012501 switch (preference.getPreference()) {
12502 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12503 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012504 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012505 if (preference.getPreferenceEnterpriseId() != 0) {
12506 throw new IllegalArgumentException(
12507 "Invalid enterprise identifier in setProfileNetworkPreferences");
12508 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012509 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012510 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12511 blockingNonEnterprise = true;
12512 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012513 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12514 allowFallback = false;
12515 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012516 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012517 // This code is needed even though there is a check later on,
12518 // because isRangeAlreadyInPreferenceList assumes that every preference
12519 // has a UID list.
12520 if (hasDefaultPreference) {
12521 throw new IllegalArgumentException(
12522 "Default profile preference should not be set along with other "
12523 + "preference");
12524 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012525 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12526 throw new IllegalArgumentException(
12527 "Invalid enterprise identifier in setProfileNetworkPreferences");
12528 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012529 final Set<UidRange> uidRangeSet =
12530 getUidListToBeAppliedForNetworkPreference(profile, preference);
12531 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12532 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12533 } else {
12534 throw new IllegalArgumentException(
12535 "Overlapping uid range in setProfileNetworkPreferences");
12536 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012537 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012538 nc.addEnterpriseId(
12539 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012540 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12541 break;
12542 default:
12543 throw new IllegalArgumentException(
12544 "Invalid preference in setProfileNetworkPreferences");
12545 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012546 preferenceList.add(new ProfileNetworkPreferenceInfo(
12547 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012548 if (hasDefaultPreference && preferenceList.size() > 1) {
12549 throw new IllegalArgumentException(
12550 "Default profile preference should not be set along with other preference");
12551 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012552 }
12553 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012554 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012555 }
12556
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012557 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12558 @NonNull final UserHandle profile,
12559 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12560 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012561 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12562 profileNetworkPreference.getIncludedUids());
12563
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012564 if (uidRangeSet.size() > 0) {
12565 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12566 throw new IllegalArgumentException(
12567 "Allow uid range is outside the uid range of profile.");
12568 }
12569 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012570 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012571 profileNetworkPreference.getExcludedUids());
12572 if (disallowUidRangeSet.size() > 0) {
12573 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12574 throw new IllegalArgumentException(
12575 "disallow uid range is outside the uid range of profile.");
12576 }
12577 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12578 disallowUidRangeSet);
12579 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012580 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012581 uidRangeSet.add(profileUids);
12582 }
12583 }
12584 return uidRangeSet;
12585 }
12586
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012587 private boolean isEnterpriseIdentifierValid(
12588 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012589 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012590 return true;
12591 }
12592 return false;
12593 }
12594
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012595 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012596 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012597 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012598 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012599 // The NRI for a user should contain the request for capabilities.
12600 // If fallback to default network is needed then NRI should include
12601 // the request for the default network. Create an image of it to
12602 // have the correct UIDs in it (also a request can only be part of one NRI, because
12603 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012604 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12605 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012606 if (pref.allowFallback) {
12607 nrs.add(createDefaultInternetRequestForTransport(
12608 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12609 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012610 if (VDBG) {
12611 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12612 pref.capabilities.getUids()));
12613 }
12614
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012615 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012616 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012617 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012618 result.add(nri);
12619 }
12620 return result;
12621 }
12622
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012623 /**
12624 * Compare if the given UID range sets have the same UIDs.
12625 *
12626 */
12627 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012628 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012629 @NonNull Set<UidRange> uidRangeSet) {
12630 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12631 return false;
12632 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012633 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012634 if (UidRangeUtils.doesRangeSetOverlap(
12635 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12636 return true;
12637 }
12638 }
12639 return false;
12640 }
12641
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012642 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012643 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012644 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012645 /*
12646 * handleSetProfileNetworkPreference is always called for single user.
12647 * preferenceList only contains preferences for different uids within the same user
12648 * (enforced by getUidListToBeAppliedForNetworkPreference).
12649 * Clear all the existing preferences for the user before applying new preferences.
12650 *
12651 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012652 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12653 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012654 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12655 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012656
paulhu74128522021-09-28 02:29:03 +000012657 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12658 addPerAppDefaultNetworkRequests(
12659 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012660 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012661
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012662 // Finally, rematch.
12663 rematchAllNetworksAndRequests();
12664
12665 if (null != listener) {
12666 try {
12667 listener.onComplete();
12668 } catch (RemoteException e) {
12669 loge("Listener for setProfileNetworkPreference has died");
12670 }
12671 }
12672 }
12673
paulhu51f77dc2021-06-07 02:34:20 +000012674 @VisibleForTesting
12675 @NonNull
12676 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12677 @NonNull final Set<Integer> uids) {
12678 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12679 if (uids.size() == 0) {
12680 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12681 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12682 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12683 return nris;
12684 }
12685
12686 final List<NetworkRequest> requests = new ArrayList<>();
12687 // The NRI should be comprised of two layers:
12688 // - The request for the mobile network preferred.
12689 // - The request for the default network, for fallback.
12690 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012691 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012692 requests.add(createDefaultInternetRequestForTransport(
12693 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12694 final Set<UidRange> ranges = new ArraySet<>();
12695 for (final int uid : uids) {
12696 ranges.add(new UidRange(uid, uid));
12697 }
12698 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012699 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012700 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012701 return nris;
12702 }
12703
12704 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012705 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012706 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12707 addPerAppDefaultNetworkRequests(
12708 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012709 // Finally, rematch.
12710 rematchAllNetworksAndRequests();
12711 }
12712
Patrick Rohr2857ac42022-01-21 14:58:16 +010012713 private void handleIngressRateLimitChanged() {
12714 final long oldIngressRateLimit = mIngressRateLimit;
12715 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12716 mContext);
12717 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12718 if (canNetworkBeRateLimited(networkAgent)) {
12719 // If rate limit has previously been enabled, remove the old limit first.
12720 if (oldIngressRateLimit >= 0) {
12721 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12722 }
12723 if (mIngressRateLimit >= 0) {
12724 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12725 mIngressRateLimit);
12726 }
12727 }
12728 }
12729 }
12730
12731 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012732 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012733 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012734
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012735 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12736 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12737 // internet connectivity can be rate limited.
12738 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12739 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012740 return false;
12741 }
12742
12743 final String iface = networkAgent.linkProperties.getInterfaceName();
12744 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012745 // This may happen in tests, but if there is no interface then there is nothing that
12746 // can be rate limited.
12747 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012748 return false;
12749 }
12750 return true;
12751 }
12752
James Mattis45d81842021-01-10 14:24:24 -080012753 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012754 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12755 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012756 }
12757
12758 /**
12759 * Used by automotive devices to set the network preferences used to direct traffic at an
12760 * application level as per the given OemNetworkPreferences. An example use-case would be an
12761 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12762 * vehicle via a particular network.
12763 *
12764 * Calling this will overwrite the existing preference.
12765 *
James Mattisda32cfe2021-01-26 16:23:52 -080012766 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012767 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012768 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012769 */
James Mattis47db0582021-01-01 14:13:35 -080012770 @Override
James Mattis45d81842021-01-10 14:24:24 -080012771 public void setOemNetworkPreference(
12772 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012773 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012774
James Mattisfa270db2021-05-31 17:11:10 -070012775 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12776 // Only bypass the permission/device checks if this is a valid test request.
12777 if (isValidTestOemNetworkPreference(preference)) {
12778 enforceManageTestNetworksPermission();
12779 } else {
12780 enforceAutomotiveDevice();
12781 enforceOemNetworkPreferencesPermission();
12782 validateOemNetworkPreferences(preference);
12783 }
James Mattis45d81842021-01-10 14:24:24 -080012784
James Mattis45d81842021-01-10 14:24:24 -080012785 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12786 new Pair<>(preference, listener)));
12787 }
12788
James Mattisfa270db2021-05-31 17:11:10 -070012789 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012790 * Sets the specified UIDs to get/receive the VPN as the only default network.
12791 *
12792 * Calling this will overwrite the existing network preference for this session, and the
12793 * specified UIDs won't get any default network when no VPN is connected.
12794 *
12795 * @param session The VPN session which manages the passed UIDs.
12796 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12797 * setting for this session if the array is empty. Null is not allowed, the
12798 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12799 * @hide
12800 */
12801 @Override
12802 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12803 Objects.requireNonNull(ranges);
12804 enforceNetworkStackOrSettingsPermission();
12805 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12806 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12807 throw new IllegalArgumentException(
12808 "setVpnNetworkPreference: Passed UID ranges overlap");
12809 }
12810
12811 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12812 new VpnNetworkPreferenceInfo(session,
12813 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12814 }
12815
12816 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12817 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12818
12819 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12820 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12821
12822 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12823 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12824 // Finally, rematch.
12825 rematchAllNetworksAndRequests();
12826 }
12827
12828 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12829 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12830 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12831 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12832 final List<NetworkRequest> requests = new ArrayList<>();
12833 // Request VPN only, so other networks won't be the fallback options when VPN is not
12834 // connected temporarily.
12835 requests.add(createVpnRequest());
12836 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12837 setNetworkRequestUids(requests, uidRanges);
12838 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12839 }
12840 return nris;
12841 }
12842
12843 /**
James Mattisfa270db2021-05-31 17:11:10 -070012844 * Check the validity of an OEM network preference to be used for testing purposes.
12845 * @param preference the preference to validate
12846 * @return true if this is a valid OEM network preference test request.
12847 */
12848 private boolean isValidTestOemNetworkPreference(
12849 @NonNull final OemNetworkPreferences preference) {
12850 // Allow for clearing of an existing OemNetworkPreference used for testing.
12851 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12852 // changes after this check is complete. This is an unlikely scenario as calling of this API
12853 // is controlled by the OEM therefore the added complexity is not worth adding given those
12854 // circumstances. That said, it is an edge case to be aware of hence this comment.
12855 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12856 && isTestOemNetworkPreference(mOemNetworkPreferences);
12857 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12858 }
12859
12860 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12861 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12862 return prefMap.size() == 1
12863 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12864 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12865 }
12866
James Mattis45d81842021-01-10 14:24:24 -080012867 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12868 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12869 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012870 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12871 throw new IllegalArgumentException(
12872 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12873 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012874 }
12875 }
12876 }
12877
12878 private void handleSetOemNetworkPreference(
12879 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012880 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012881 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12882 if (DBG) {
12883 log("set OEM network preferences :" + preference.toString());
12884 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012885
James Mattiscb1e0362021-04-06 17:07:42 -070012886 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012887 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12888 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12889 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012890 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012891
12892 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012893 try {
12894 listener.onComplete();
12895 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012896 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012897 }
James Mattis45d81842021-01-10 14:24:24 -080012898 }
12899 }
12900
paulhu74128522021-09-28 02:29:03 +000012901 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012902 // Skip the requests which are set by other network preference. Because the uid range rules
12903 // should stay in netd.
12904 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012905 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012906 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012907 }
12908
James Mattis3ce3d3c2021-02-09 18:18:28 -080012909 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12910 ensureRunningOnConnectivityServiceThread();
12911 mDefaultNetworkRequests.addAll(nris);
12912 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12913 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012914 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012915 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12916 nrisToRegister.addAll(
12917 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12918 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012919 }
12920
12921 /**
12922 * All current requests that are tracking the default network need to be assessed as to whether
12923 * or not the current set of per-application default requests will be changing their default
12924 * network. If so, those requests will need to be updated so that they will send callbacks for
12925 * default network changes at the appropriate time. Additionally, those requests tracking the
12926 * default that were previously updated by this flow will need to be reassessed.
12927 * @return the nris which will need to be updated.
12928 */
12929 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12930 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12931 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12932 // same nri in the map's values for each of its NetworkRequest objects.
12933 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012934 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012935 // Include this nri if it is currently being tracked.
12936 if (isPerAppTrackedNri(nri)) {
12937 defaultCallbackRequests.add(nri);
12938 continue;
12939 }
12940 // We only track callbacks for requests tracking the default.
12941 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12942 continue;
12943 }
12944 // Include this nri if it will be tracked by the new per-app default requests.
12945 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012946 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012947 if (isNriGoingToBeTracked) {
12948 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012949 }
12950 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012951 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012952 }
12953
James Mattis3ce3d3c2021-02-09 18:18:28 -080012954 /**
12955 * Create nris for those network requests that are currently tracking the default network that
12956 * are being controlled by a per-application default.
12957 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12958 * foundation when creating the nri. Important items include the calling uid's original
12959 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12960 * requests are assumed to have already been validated as needing to be updated.
12961 * @return the Set of nris to use when registering network requests.
12962 */
12963 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12964 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12965 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12966 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12967 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012968 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012969
Chalard Jean9473c982021-07-29 20:03:04 +090012970 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012971 if (trackingNri == mDefaultRequest) {
12972 callbackRequestsToRegister.add(new NetworkRequestInfo(
12973 callbackRequest,
12974 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12975 continue;
12976 }
12977
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012978 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012979 callbackRequestsToRegister.add(new NetworkRequestInfo(
12980 callbackRequest,
12981 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012982 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012983 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012984 }
12985 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012986 }
12987
Chalard Jean17215832021-03-01 14:06:28 +090012988 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12989 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012990 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012991 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012992 }
12993 }
12994
James Mattis45d81842021-01-10 14:24:24 -080012995 /**
12996 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12997 */
12998 @VisibleForTesting
12999 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013000 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080013001 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013002 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080013003 final SparseArray<Set<Integer>> uids =
13004 createUidsFromOemNetworkPreferences(preference);
13005 for (int i = 0; i < uids.size(); i++) {
13006 final int key = uids.keyAt(i);
13007 final Set<Integer> value = uids.valueAt(i);
13008 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
13009 // No need to add an nri without any requests.
13010 if (0 == nri.mRequests.size()) {
13011 continue;
13012 }
13013 nris.add(nri);
13014 }
13015
13016 return nris;
13017 }
13018
13019 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
13020 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070013021 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080013022 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080013023 final List<UserHandle> users =
13024 mContext.getSystemService(UserManager.class).getUserHandles(true);
13025 if (null == users || users.size() == 0) {
13026 if (VDBG || DDBG) {
13027 log("No users currently available for setting the OEM network preference.");
13028 }
James Mattisb6b6a432021-06-01 22:30:36 -070013029 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080013030 }
James Mattis45d81842021-01-10 14:24:24 -080013031 for (final Map.Entry<String, Integer> entry :
13032 preference.getNetworkPreferences().entrySet()) {
13033 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070013034 // Add the rules for all users as this policy is device wide.
13035 for (final UserHandle user : users) {
13036 try {
13037 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
13038 if (!prefToUids.contains(pref)) {
13039 prefToUids.put(pref, new ArraySet<>());
13040 }
13041 prefToUids.get(pref).add(uid);
13042 } catch (PackageManager.NameNotFoundException e) {
13043 // Although this may seem like an error scenario, it is ok that uninstalled
13044 // packages are sent on a network preference as the system will watch for
13045 // package installations associated with this network preference and update
13046 // accordingly. This is done to minimize race conditions on app install.
13047 continue;
James Mattis45d81842021-01-10 14:24:24 -080013048 }
James Mattis45d81842021-01-10 14:24:24 -080013049 }
13050 }
James Mattisb6b6a432021-06-01 22:30:36 -070013051 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080013052 }
13053
13054 private NetworkRequestInfo createNriFromOemNetworkPreferences(
13055 @OemNetworkPreferences.OemNetworkPreference final int preference,
13056 @NonNull final Set<Integer> uids) {
13057 final List<NetworkRequest> requests = new ArrayList<>();
13058 // Requests will ultimately be evaluated by order of insertion therefore it matters.
13059 switch (preference) {
13060 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
13061 requests.add(createUnmeteredNetworkRequest());
13062 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070013063 requests.add(createDefaultInternetRequestForTransport(
13064 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080013065 break;
13066 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
13067 requests.add(createUnmeteredNetworkRequest());
13068 requests.add(createOemPaidNetworkRequest());
13069 break;
13070 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
13071 requests.add(createOemPaidNetworkRequest());
13072 break;
13073 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
13074 requests.add(createOemPrivateNetworkRequest());
13075 break;
James Mattisfa270db2021-05-31 17:11:10 -070013076 case OEM_NETWORK_PREFERENCE_TEST:
13077 requests.add(createUnmeteredNetworkRequest());
13078 requests.add(createTestNetworkRequest());
13079 requests.add(createDefaultRequest());
13080 break;
13081 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
13082 requests.add(createTestNetworkRequest());
13083 break;
James Mattis45d81842021-01-10 14:24:24 -080013084 default:
13085 // This should never happen.
13086 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
13087 + " called with invalid preference of " + preference);
13088 }
13089
James Mattisfa270db2021-05-31 17:11:10 -070013090 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090013091 for (final int uid : uids) {
13092 ranges.add(new UidRange(uid, uid));
13093 }
13094 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080013095 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080013096 }
13097
13098 private NetworkRequest createUnmeteredNetworkRequest() {
13099 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13100 .addCapability(NET_CAPABILITY_NOT_METERED)
13101 .addCapability(NET_CAPABILITY_VALIDATED);
13102 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
13103 }
13104
13105 private NetworkRequest createOemPaidNetworkRequest() {
13106 // NET_CAPABILITY_OEM_PAID is a restricted capability.
13107 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13108 .addCapability(NET_CAPABILITY_OEM_PAID)
13109 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13110 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13111 }
13112
13113 private NetworkRequest createOemPrivateNetworkRequest() {
13114 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
13115 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13116 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
13117 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13118 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13119 }
13120
13121 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070013122 final NetworkCapabilities netcap = new NetworkCapabilities();
13123 netcap.addCapability(NET_CAPABILITY_INTERNET);
13124 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
13125 return netcap;
13126 }
13127
13128 private NetworkRequest createTestNetworkRequest() {
13129 final NetworkCapabilities netcap = new NetworkCapabilities();
13130 netcap.clearAll();
13131 netcap.addTransportType(TRANSPORT_TEST);
13132 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080013133 }
James Mattis47db0582021-01-01 14:13:35 -080013134 }
markchien738ad912021-12-09 18:15:45 +080013135
Junyu Lai38c75032023-12-04 07:52:19 +000013136 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080013137 @Override
Junyu Laidf210362023-10-24 02:47:50 +000013138 public void setDataSaverEnabled(final boolean enable) {
13139 enforceNetworkStackOrSettingsPermission();
13140 try {
13141 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
13142 if (!ret) {
13143 throw new IllegalStateException("Error when changing iptables: " + enable);
13144 }
13145 } catch (RemoteException e) {
13146 // Lack of permission or binder errors.
13147 throw new IllegalStateException(e);
13148 }
Ken Chen24330172023-10-20 13:02:14 +080013149
13150 try {
13151 mBpfNetMaps.setDataSaverEnabled(enable);
13152 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13153 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13154 }
Junyu Laidf210362023-10-24 02:47:50 +000013155 }
13156
13157 @Override
markchien738ad912021-12-09 18:15:45 +080013158 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13159 enforceNetworkStackOrSettingsPermission();
13160
13161 try {
13162 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013163 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013164 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013165 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013166 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013167 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013168 throw new IllegalStateException(e);
13169 }
13170 }
13171
13172 @Override
13173 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13174 enforceNetworkStackOrSettingsPermission();
13175
13176 try {
13177 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013178 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013179 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013180 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013181 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013182 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013183 throw new IllegalStateException(e);
13184 }
13185 }
markchiene1561fa2021-12-09 22:00:56 +080013186
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013187 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13188 throws PackageManager.NameNotFoundException {
13189 final PackageManager pm = mContext.getPackageManager();
13190 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13191 if (appId < Process.FIRST_APPLICATION_UID) {
13192 throw new RuntimeException("Can't set package firewall rule for system app "
13193 + packageName + " with appId " + appId);
13194 }
13195 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13196 final int uid = uh.getUid(appId);
13197 setUidFirewallRule(chain, uid, rule);
13198 }
13199 return appId;
13200 }
13201
markchiene1561fa2021-12-09 22:00:56 +080013202 @Override
markchien3c04e662022-03-22 16:29:56 +080013203 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013204 enforceNetworkStackOrSettingsPermission();
13205
markchien3c04e662022-03-22 16:29:56 +080013206 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13207 int firewallRule = getFirewallRuleType(chain, rule);
13208
13209 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13210 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13211 }
13212
markchiene1561fa2021-12-09 22:00:56 +080013213 try {
markchien3c04e662022-03-22 16:29:56 +080013214 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013215 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013216 throw new IllegalStateException(e);
13217 }
13218 }
markchien98a6f952022-01-13 23:43:53 +080013219
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013220 private int getPackageFirewallRule(final int chain, final String packageName)
13221 throws PackageManager.NameNotFoundException {
13222 final PackageManager pm = mContext.getPackageManager();
13223 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13224 return getUidFirewallRule(chain, appId);
13225 }
13226
Motomu Utsumi900b8062023-01-19 16:16:49 +090013227 @Override
13228 public int getUidFirewallRule(final int chain, final int uid) {
13229 enforceNetworkStackOrSettingsPermission();
13230 return mBpfNetMaps.getUidRule(chain, uid);
13231 }
13232
markchien3c04e662022-03-22 16:29:56 +080013233 private int getFirewallRuleType(int chain, int rule) {
13234 final int defaultRule;
13235 switch (chain) {
13236 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013237 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13238 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013239 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013240 defaultRule = FIREWALL_RULE_ALLOW;
13241 break;
13242 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13243 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13244 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13245 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013246 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013247 defaultRule = FIREWALL_RULE_DENY;
13248 break;
13249 default:
13250 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13251 }
13252 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13253
13254 return rule;
13255 }
13256
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013257 private void closeSocketsForFirewallChainLocked(final int chain)
13258 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013259 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013260 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13261 // So, close all non-system socket owned by uids that are not explicitly allowed
13262 Set<Range<Integer>> ranges = new ArraySet<>();
13263 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13264 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13265 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13266 } else {
13267 // Denylist means the firewall allows all by default, uids must be explicitly denied
13268 // So, close socket owned by uids that are explicitly denied
13269 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13270 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13271 }
13272 }
13273
markchien98a6f952022-01-13 23:43:53 +080013274 @Override
13275 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13276 enforceNetworkStackOrSettingsPermission();
13277
13278 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013279 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013280 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013281 throw new IllegalStateException(e);
13282 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013283
Chalard Jeandf29a852023-05-29 17:02:43 +090013284 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013285 try {
13286 closeSocketsForFirewallChainLocked(chain);
13287 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13288 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13289 }
13290 }
markchien98a6f952022-01-13 23:43:53 +080013291 }
13292
markchien00a0bed2022-01-13 23:46:13 +080013293 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013294 public boolean getFirewallChainEnabled(final int chain) {
13295 enforceNetworkStackOrSettingsPermission();
13296
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013297 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013298 }
13299
13300 @Override
markchien00a0bed2022-01-13 23:46:13 +080013301 public void replaceFirewallChain(final int chain, final int[] uids) {
13302 enforceNetworkStackOrSettingsPermission();
13303
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013304 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013305 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013306
13307 @Override
13308 public IBinder getCompanionDeviceManagerProxyService() {
13309 enforceNetworkStackPermission(mContext);
13310 return mCdmps;
13311 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013312
13313 @Override
13314 public IBinder getRoutingCoordinatorService() {
13315 enforceNetworkStackPermission(mContext);
13316 return mRoutingCoordinatorService;
13317 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013318}