blob: a995439d1d45f31b82833e08bf51196f7dc91293 [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;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800111import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800112import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
113import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
114import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900115import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900116
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800117import static java.util.Map.Entry;
118
Chalard Jean5b639762020-03-09 21:25:37 +0900119import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000120import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800121import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600122import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800123import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000124import android.app.ActivityManager;
125import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800126import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800127import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700128import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700129import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900130import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800131import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700132import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800133import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800134import android.content.ContentResolver;
135import android.content.Context;
136import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700137import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800138import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900139import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700140import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800141import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900142import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900143import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700144import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800145import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800146import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800147import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900148import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800149import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900150import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800151import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900152import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800153import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700154import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900155import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800156import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800158import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800159import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800160import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900161import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900162import android.net.INetworkMonitor;
163import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900164import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900165import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700166import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800167import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900168import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900169import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900170import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800171import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900172import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900173import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100174import android.net.MatchAllNetworkSpecifier;
Yang Sun29037f62023-12-04 10:31:58 +0800175import android.net.MulticastRoutingConfig;
Ken Chen6df7a902021-04-09 15:08:42 +0800176import android.net.NativeNetworkConfig;
177import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800178import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700179import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700180import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900181import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700182import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800183import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700184import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900185import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900186import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000187import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900188import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700189import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900190import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700191import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900192import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700193import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800194import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900195import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700196import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000197import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800198import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900199import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800200import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400201import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700202import android.net.QosCallbackException;
203import android.net.QosFilter;
204import android.net.QosSocketFilter;
205import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700206import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800207import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800208import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900209import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400210import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800211import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800212import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400213import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800214import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900215import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900216import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900217import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900218import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800219import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900220import android.net.networkstack.ModuleNetworkStackClient;
221import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900222import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800223import android.net.resolv.aidl.DnsHealthEventParcel;
224import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
225import android.net.resolv.aidl.Nat64PrefixEventParcel;
226import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900227import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900228import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800229import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800231import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700232import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000233import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800234import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700235import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700236import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800237import android.os.Looper;
238import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700239import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700240import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900241import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800242import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700243import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700244import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800245import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700246import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900247import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900248import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700249import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700250import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400251import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800252import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900253import android.stats.connectivity.MeteredState;
254import android.stats.connectivity.RequestType;
255import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900256import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700257import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700258import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700259import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800260import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900261import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000262import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600263import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900264import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900265import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700266import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700267import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900268import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800269
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800270import androidx.annotation.RequiresApi;
271
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900272import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400273import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400274import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700275import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900276import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900277import com.android.metrics.ConnectionDurationForTransports;
278import com.android.metrics.ConnectionDurationPerTransports;
279import com.android.metrics.ConnectivitySampleMetricsHelper;
280import com.android.metrics.ConnectivityStateSample;
281import com.android.metrics.NetworkCountForTransports;
282import com.android.metrics.NetworkCountPerTransports;
283import com.android.metrics.NetworkDescription;
284import com.android.metrics.NetworkList;
285import com.android.metrics.NetworkRequestCount;
286import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800287import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900288import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800289import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000290import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900291import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800292import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900293import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900294import com.android.net.module.util.DeviceConfigUtils;
Junyu Lai2ff42d22023-12-07 16:57:13 +0800295import com.android.net.module.util.HandlerUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100296import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900297import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
298import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900299import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800300import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800301import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100302import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000303import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800304import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
305import com.android.networkstack.apishim.ConstantsShim;
306import com.android.networkstack.apishim.common.BroadcastOptionsShim;
307import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900308import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900309import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000310import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900311import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800312import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800313import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900314import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900315import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900316import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500317import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700318import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900319import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900320import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900321import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000322import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100323import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700324import com.android.server.connectivity.MockableSystemProperties;
Yang Sun29037f62023-12-04 10:31:58 +0800325import com.android.server.connectivity.MulticastRoutingCoordinatorService;
Chalard Jean43aae652022-09-14 21:33:06 +0900326import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700327import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600328import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900329import com.android.server.connectivity.NetworkNotificationManager;
330import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900331import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900332import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900333import com.android.server.connectivity.NetworkRanker;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000334import com.android.server.connectivity.NetworkRequestStateStatsMetrics;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700335import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900336import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900337import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700338import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900339import com.android.server.connectivity.RoutingCoordinatorService;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800340import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000341import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800342import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600343
Josh Gao461a1222020-06-16 15:58:11 -0700344import libcore.io.IoUtils;
345
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900346import org.xmlpull.v1.XmlPullParserException;
347
The Android Open Source Project28527d22009-03-03 19:31:44 -0800348import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100349import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900350import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800351import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900352import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700353import java.net.Inet4Address;
Yang Sun29037f62023-12-04 10:31:58 +0800354import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700355import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900356import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900357import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700358import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700359import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700360import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700361import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800362import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900363import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800364import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700365import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700366import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700367import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700368import java.util.Map;
Yang Sun29037f62023-12-04 10:31:58 +0800369import java.util.Map.Entry;
Chalard Jean524f0b12021-10-25 21:11:56 +0900370import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700371import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900372import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600373import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900374import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600375import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900376import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900377import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800378
379/**
380 * @hide
381 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800382public class ConnectivityService extends IConnectivityManager.Stub
383 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900384 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800385
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900386 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900387 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900388 private static final String NETWORK_ARG = "networks";
389 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800390 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900391
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900392 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900393 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
394 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800395
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900396 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700397
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100398 /**
399 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
400 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800401 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100402 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
403 * (preferably via runtime resource overlays).
404 */
405 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
406 "http://connectivitycheck.gstatic.com/generate_204";
407
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700408 // TODO: create better separation between radio types and network types
409
Robert Greenwalt2034b912009-08-12 16:08:25 -0700410 // how long to wait before switching back to a radio's default network
411 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
412 // system property that can override the above value
413 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
414 "android.telephony.apn-restore";
415
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900416 // How long to wait before putting up a "This network doesn't have an Internet connection,
417 // connect anyway?" dialog after the user selects a network that doesn't validate.
418 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
419
Chalard Jean5fb43c72022-09-08 19:03:14 +0900420 // How long to wait before considering that a network is bad in the absence of any form
421 // of connectivity (valid, partial, captive portal). If none has been detected after this
422 // delay, the stack considers this network bad, which may affect how it's handled in ranking
423 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900424 // Timeout in case the "actively prefer bad wifi" feature is on
425 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
426 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900427 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900428
junyulai0ac374f2020-12-14 18:41:52 +0800429 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900430 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
431 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800432 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700433
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800434 // Delimiter used when creating the broadcast delivery group for sending
435 // CONNECTIVITY_ACTION broadcast.
436 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
437
he_won.hwang881307a2022-03-15 21:23:52 +0900438 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900439 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900440
Daniel Brightf9e945b2020-06-15 16:10:01 -0700441 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900442 @VisibleForTesting
443 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700444
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900445 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700446 @VisibleForTesting
447 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900448
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900449 @VisibleForTesting
450 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800451 @VisibleForTesting
452 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900453 // True if the cell radio of the device is capable of time-sharing.
454 @VisibleForTesting
455 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900456
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800457 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800458 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800459 private final int mReleasePendingIntentDelayMs;
460
Chalard Jean46bfbf02022-02-02 00:56:25 +0900461 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900462
Motomu Utsumif360aa62023-01-30 17:52:20 +0900463 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700464
Chalard Jean9473c982021-07-29 20:03:04 +0900465 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800466 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700467 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800468 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700469
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900470 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700471
junyulaif2c67e42018-08-07 19:50:45 +0800472 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000473 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
474 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800475 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900476 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800477
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900478 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900479 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000480 private final int mWakeUpMark;
481 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000482 // The Context is created for UserHandle.ALL.
483 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900484 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900485 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700486 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700487 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800488
Chenbo Feng15416292018-11-08 17:36:21 -0800489 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800490 protected IDnsResolver mDnsResolver;
491 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800492 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700493 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900494 private final NetworkStatsManager mStatsManager;
495 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800496 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700497
Benedict Wong493e04b2018-11-09 14:45:34 -0800498 /**
499 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
500 * instances.
501 */
502 @GuardedBy("mTNSLock")
503 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800504 private final CompanionDeviceManagerProxyService mCdmps;
Yang Sun29037f62023-12-04 10:31:58 +0800505 private final MulticastRoutingCoordinatorService mMulticastRoutingCoordinatorService;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900506 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800507
508 private final Object mTNSLock = new Object();
509
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700510 private String mCurrentTcpBufferSizes;
511
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900512 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000513 new Class[] {
514 ConnectivityService.class,
515 NetworkAgent.class,
516 NetworkAgentInfo.class,
517 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900518
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500519 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400520 // Tear down networks that have no chance (e.g. even if validated) of becoming
521 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500522 // all networks have been rematched against all NetworkRequests.
523 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400524 // Don't reap networks. This should be passed when some networks have not yet been
525 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500526 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900527 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500528
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900529 private enum UnneededFor {
530 LINGER, // Determine whether this network is unneeded and should be lingered.
531 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
532 }
533
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700534 /**
paulhuaa0743d2021-05-26 21:56:03 +0800535 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800536 * should have priority. The order is passed to netd which will use it together
537 * with UID ranges to generate the corresponding IP rule. This serves to
538 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800539 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800540 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000541 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800542 *
paulhu48291862021-07-14 14:53:57 +0800543 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
544 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800545 */
paulhu48291862021-07-14 14:53:57 +0800546 // Used when sending to netd to code for "no order".
547 static final int PREFERENCE_ORDER_NONE = 0;
548 // Order for requests that don't code for a per-app preference. As it is
549 // out of the valid range, the corresponding order should be
550 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800551 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800552 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800553 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800554 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
555 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800556 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800557 static final int PREFERENCE_ORDER_OEM = 10;
558 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800559 // See {@link #setProfileNetworkPreference}.
560 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800561 static final int PREFERENCE_ORDER_PROFILE = 20;
562 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800563 // better scores are connected.
564 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800565 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800566 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900567 // Preference order that signifies the network shouldn't be set as a default network for
568 // the UIDs, only give them access to it. TODO : replace this with a boolean
569 // in NativeUidRangeConfig
570 @VisibleForTesting
571 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
572 // Bound for the lowest valid preference order.
573 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800574
575 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700576 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700577 * from one net to another. Clear happens when we get a new
578 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
579 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700580 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700581 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700582
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700583 /**
584 * used internally to reload global proxy settings
585 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700586 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700587
Robert Greenwalt34848c02011-03-25 13:09:25 -0700588 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400589 * PAC manager has received new port.
590 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800591 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400592
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700593 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900594 * used internally when registering NetworkProviders
595 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700596 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900597 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700598
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700599 /**
600 * used internally when registering NetworkAgents
601 * obj = Messenger
602 */
603 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
604
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700605 /**
606 * used to add a network request
607 * includes a NetworkRequestInfo
608 */
609 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
610
611 /**
612 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900613 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700614 * cancel it.
615 * includes a NetworkRequestInfo
616 */
617 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
618
619 /**
620 * used to add a network listener - no request
621 * includes a NetworkRequestInfo
622 */
623 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
624
625 /**
626 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400627 * arg1 = UID of caller
628 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700629 */
630 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
631
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700632 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900633 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700634 * obj = Messenger
635 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900636 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700637
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700638 /**
639 * used internally to expire a wakelock when transitioning
640 * from one net to another. Expire happens when we fail to find
641 * a new network (typically after 1 minute) -
642 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
643 * a replacement network.
644 */
645 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
646
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700647 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800648 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400649 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800650 */
651 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
652
653 /**
654 * used to remove a pending intent and its associated network request.
655 * arg1 = UID of caller
656 * obj = PendingIntent
657 */
658 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
659
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900660 /**
661 * used to specify whether a network should be used even if unvalidated.
662 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
663 * arg2 = whether to remember this choice in the future (1 or 0)
664 * obj = network
665 */
666 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
667
668 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700669 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900670 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700671 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900672
Paul Jensenc8873fc2015-06-17 14:15:39 -0400673 /**
674 * used to add a network listener with a pending intent
675 * obj = NetworkRequestInfo
676 */
677 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
678
Hugo Benichid6b510a2017-04-06 17:22:18 +0900679 /**
680 * used to specify whether a network should not be penalized when it becomes unvalidated.
681 */
682 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
683
684 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700685 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900686 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700687 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900688
Erik Kline31b4a9e2018-01-11 21:07:29 +0900689 // Handle changes in Private DNS settings.
690 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
691
dalyk1720e542018-03-05 12:42:22 -0500692 // Handle private DNS validation status updates.
693 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
694
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900695 /**
696 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
697 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800698 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
699 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
700 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900701 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900702 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900703
704 /**
705 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
706 * config was resolved.
707 * obj = PrivateDnsConfig
708 * arg2 = netid
709 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900710 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900711
712 /**
713 * Request ConnectivityService display provisioning notification.
714 * arg1 = Whether to make the notification visible.
715 * arg2 = NetID.
716 * obj = Intent to be launched when notification selected by user, null if !arg1.
717 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900718 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900719
720 /**
lucaslin2240ef62019-03-12 13:08:03 +0800721 * Used to specify whether a network should be used even if connectivity is partial.
722 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
723 * false)
724 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
725 * obj = network
726 */
lucaslin444d43a2020-02-20 16:56:59 +0800727 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800728
729 /**
lucasline117e2e2019-10-22 18:27:33 +0800730 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
731 * Both of the arguments are bitmasks, and the value of bits come from
732 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900733 * arg1 = unused
734 * arg2 = netId
735 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800736 */
lucaslin444d43a2020-02-20 16:56:59 +0800737 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800738
739 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900740 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
741 * arg1 = unused
742 * arg2 = netId
743 * obj = captive portal data
744 */
lucaslin444d43a2020-02-20 16:56:59 +0800745 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900746
747 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900748 * Used by setRequireVpnForUids.
749 * arg1 = whether the specified UID ranges are required to use a VPN.
750 * obj = Array of UidRange objects.
751 */
752 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
753
754 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900755 * Used internally when setting the default networks for OemNetworkPreferences.
756 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800757 */
758 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
759
760 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800761 * Used to indicate the system default network becomes active.
762 */
763 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
764
765 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900766 * Used internally when setting a network preference for a user profile.
767 * obj = Pair<ProfileNetworkPreference, Listener>
768 */
769 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
770
771 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000772 * Event to specify that reasons for why an uid is blocked changed.
773 * arg1 = uid
774 * arg2 = blockedReasons
775 */
776 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
777
778 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900779 * Event to register a new network offer
780 * obj = NetworkOffer
781 */
782 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
783
784 /**
785 * Event to unregister an existing network offer
786 * obj = INetworkOfferCallback
787 */
788 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
789
790 /**
paulhu51f77dc2021-06-07 02:34:20 +0000791 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
792 */
793 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
794
795 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800796 * Event to set temporary allow bad wifi within a limited time to override
797 * {@code config_networkAvoidBadWifi}.
798 */
799 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
800
801 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100802 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
803 */
804 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
805
806 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900807 * The initial evaluation period is over for this network.
808 *
809 * If no form of connectivity has been found on this network (valid, partial, captive portal)
810 * then the stack will now consider it to have been determined bad.
811 */
812 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
813
814 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000815 * Used internally when the user does not want the network from captive portal app.
816 * obj = Network
817 */
818 private static final int EVENT_USER_DOES_NOT_WANT = 58;
819
820 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000821 * Event to set VPN as preferred network for specific apps.
822 * obj = VpnNetworkPreferenceInfo
823 */
824 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
825
826 /**
chiachangwange0192a72023-02-06 13:25:01 +0000827 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
828 */
829 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
830
831 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000832 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
833 */
834 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
835
836 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900837 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
838 * should be shown.
839 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900840 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900841
842 /**
843 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
844 * should be hidden.
845 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900846 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900847
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800848 /**
849 * The maximum alive time to allow bad wifi configuration for testing.
850 */
851 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
852
Patrick Rohr2857ac42022-01-21 14:58:16 +0100853 /**
chiachangwange0192a72023-02-06 13:25:01 +0000854 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
855 * testing.
856 */
857 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
858
859 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100860 * The priority of the tc police rate limiter -- smaller value is higher priority.
861 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
862 */
863 private static final short TC_PRIO_POLICE = 1;
864
865 /**
866 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
867 */
868 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700869 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100870
Hugo Benichi47011212017-03-30 10:46:05 +0900871 private static String eventName(int what) {
872 return sMagicDecoderRing.get(what, Integer.toString(what));
873 }
874
paulhua10d8212020-11-10 15:32:56 +0800875 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900876 final DnsResolverServiceManager dsm = context.getSystemService(
877 DnsResolverServiceManager.class);
878 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800879 }
880
Cody Kesting73708bf2019-12-18 10:57:50 -0800881 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900882 @VisibleForTesting
883 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700884 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700885 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700886 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700887 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800888 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
889 @VisibleForTesting
890 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
891
Erik Kline32120082017-12-13 19:40:49 +0900892 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900893 @VisibleForTesting
894 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700895
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400896 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800897 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400898
Chalard Jean46bfbf02022-02-02 00:56:25 +0900899 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800900 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700901
Chalard Jean5d70ba42018-06-07 16:44:04 +0900902 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
903 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800904 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400905
Erik Kline05f2b402015-04-30 12:58:40 +0900906 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700907
Chalard Jean46bfbf02022-02-02 00:56:25 +0900908 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400909
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700910 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900911 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700912
Valentin Iftime9fa35092019-09-24 13:32:13 +0200913 private Set<String> mWolSupportedInterfaces;
914
Roshan Pius08c94fb2020-01-16 12:17:17 -0800915 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800916 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800917 private final AppOpsManager mAppOpsManager;
918
919 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400920
chiachangwang3d60bac2023-01-17 14:38:08 +0000921 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900922 private final QosCallbackTracker mQosCallbackTracker;
923 private final NetworkNotificationManager mNotifier;
924 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900925
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700926 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800927 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700928
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900929 // Sequence number for NetworkProvider IDs.
930 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
931 NetworkProvider.FIRST_PROVIDER_ID);
932
Erik Klineedf878b2015-07-09 18:24:03 +0900933 // NetworkRequest activity String log entries.
934 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
935 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
936
Hugo Benichid159fdd2016-07-11 11:05:12 +0900937 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900938 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900939 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
940
Hugo Benichi47011212017-03-30 10:46:05 +0900941 private static final int MAX_WAKELOCK_LOGS = 20;
942 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900943 private int mTotalWakelockAcquisitions = 0;
944 private int mTotalWakelockReleases = 0;
945 private long mTotalWakelockDurationMs = 0;
946 private long mMaxWakelockDurationMs = 0;
947 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900948
Hugo Benichi208c0102016-07-28 17:53:06 +0900949 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900950
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000951 @Nullable private final NetworkRequestStateStatsMetrics mNetworkRequestStateStatsMetrics;
952
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700953 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900954 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700955
Erik Kline95ecfee2016-10-02 18:02:14 +0900956 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900957 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900958
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900959 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800960 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
961 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800962
Patrick Rohr2857ac42022-01-21 14:58:16 +0100963 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
964 // configured via {@link
965 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
966 // Only the handler thread is allowed to access this field.
967 private long mIngressRateLimit = -1;
968
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900969 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
970 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900971 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900972 @GuardedBy("mSelfCertifiedCapabilityCache")
973 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
974 mSelfCertifiedCapabilityCache = new HashMap<>();
975
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900976 // Flag to enable the feature of closing frozen app sockets.
977 private final boolean mDestroyFrozenSockets;
978
979 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
980 private final boolean mDelayDestroyFrozenSockets;
981
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900982 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
983 private final boolean mAllowSysUiConnectivityReports;
984
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900985 // Uids that ConnectivityService is pending to close sockets of.
986 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
987
Robert Greenwalt802c1102014-06-02 15:32:02 -0700988 /**
989 * Implements support for the legacy "one network per network type" model.
990 *
991 * We used to have a static array of NetworkStateTrackers, one for each
992 * network type, but that doesn't work any more now that we can have,
993 * for example, more that one wifi network. This class stores all the
994 * NetworkAgentInfo objects that support a given type, but the legacy
995 * API will only see the first one.
996 *
997 * It serves two main purposes:
998 *
999 * 1. Provide information about "the network for a given type" (since this
1000 * API only supports one).
1001 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
1002 * the first network for a given type changes, or if the default network
1003 * changes.
1004 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001005 @VisibleForTesting
1006 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001007
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09001008 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001009 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001010
Robert Greenwalt802c1102014-06-02 15:32:02 -07001011 /**
1012 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1013 * Each list holds references to all NetworkAgentInfos that are used to
1014 * satisfy requests for that network type.
1015 *
1016 * This array is built out at startup such that an unsupported network
1017 * doesn't get an ArrayList instance, making this a tristate:
1018 * unsupported, supported but not active and active.
1019 *
1020 * The actual lists are populated when we scan the network types that
1021 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001022 *
1023 * Threading model:
1024 * - addSupportedType() is only called in the constructor
1025 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1026 * They are therefore not thread-safe with respect to each other.
1027 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1028 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001029 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001030 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001031 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001032 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001033 @NonNull
1034 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001035
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001036 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1037 // an entry have no timer (equivalent to -1). Lazily loaded.
1038 @NonNull
1039 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1040
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001041 LegacyTypeTracker(@NonNull ConnectivityService service) {
1042 mService = service;
1043 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001044 }
1045
Chiachang Wang3bc52762021-11-25 14:17:57 +08001046 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1047 // addressed.
1048 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001049 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1050 final PackageManager pm = ctx.getPackageManager();
1051 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1052 addSupportedType(TYPE_WIFI);
1053 }
1054 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1055 addSupportedType(TYPE_WIFI_P2P);
1056 }
1057 if (tm.isDataCapable()) {
1058 // Telephony does not have granular support for these types: they are either all
1059 // supported, or none is supported
1060 addSupportedType(TYPE_MOBILE);
1061 addSupportedType(TYPE_MOBILE_MMS);
1062 addSupportedType(TYPE_MOBILE_SUPL);
1063 addSupportedType(TYPE_MOBILE_DUN);
1064 addSupportedType(TYPE_MOBILE_HIPRI);
1065 addSupportedType(TYPE_MOBILE_FOTA);
1066 addSupportedType(TYPE_MOBILE_IMS);
1067 addSupportedType(TYPE_MOBILE_CBS);
1068 addSupportedType(TYPE_MOBILE_IA);
1069 addSupportedType(TYPE_MOBILE_EMERGENCY);
1070 }
1071 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1072 addSupportedType(TYPE_BLUETOOTH);
1073 }
1074 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1075 // TYPE_PROXY is only used on Wear
1076 addSupportedType(TYPE_PROXY);
1077 }
1078 // Ethernet is often not specified in the configs, although many devices can use it via
1079 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001080 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001081 addSupportedType(TYPE_ETHERNET);
1082 }
1083
1084 // Always add TYPE_VPN as a supported type
1085 addSupportedType(TYPE_VPN);
1086 }
1087
1088 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001089 if (mTypeLists[type] != null) {
1090 throw new IllegalStateException(
1091 "legacy list for type " + type + "already initialized");
1092 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001093 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001094 }
1095
Robert Greenwalt802c1102014-06-02 15:32:02 -07001096 public boolean isTypeSupported(int type) {
1097 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1098 }
1099
1100 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001101 synchronized (mTypeLists) {
1102 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1103 return mTypeLists[type].get(0);
1104 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001105 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001106 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001107 }
1108
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001109 public int getRestoreTimerForType(int type) {
1110 synchronized (mTypeLists) {
1111 if (mRestoreTimers == null) {
1112 mRestoreTimers = loadRestoreTimers();
1113 }
1114 return mRestoreTimers.getOrDefault(type, -1);
1115 }
1116 }
1117
1118 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1119 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001120 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001121 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1122 for (final String config : configs) {
1123 final String[] splits = TextUtils.split(config, ",");
1124 if (splits.length != 2) {
1125 logwtf("Invalid restore timer token count: " + config);
1126 continue;
1127 }
1128 try {
1129 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1130 } catch (NumberFormatException e) {
1131 logwtf("Invalid restore timer number format: " + config, e);
1132 }
1133 }
1134 return ret;
1135 }
1136
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001137 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001138 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001139 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001140 log("Sending " + state
1141 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001142 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001143 }
1144 }
1145
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001146 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1147 // network type, to preserve previous behaviour.
1148 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1149 if (vpnNai != mService.getLegacyLockdownNai()) return;
1150
1151 if (vpnNai.declaredUnderlyingNetworks == null
1152 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1153 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1154 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1155 return;
1156 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001157 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001158 vpnNai.declaredUnderlyingNetworks[0]);
1159 if (underlyingNai == null) return;
1160
1161 final int type = underlyingNai.networkInfo.getType();
1162 final DetailedState state = DetailedState.CONNECTED;
1163 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1164 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1165 }
1166
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001167 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001168 public void add(int type, NetworkAgentInfo nai) {
1169 if (!isTypeSupported(type)) {
1170 return; // Invalid network type.
1171 }
1172 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1173
1174 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1175 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001176 return;
1177 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001178 synchronized (mTypeLists) {
1179 list.add(nai);
1180 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001181
Chalard Jean5b409c72021-02-04 13:12:59 +09001182 // Send a broadcast if this is the first network of its type or if it's the default.
1183 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001184
1185 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1186 // to preserve previous behaviour.
1187 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001188 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001189 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1190 mService.sendLegacyNetworkBroadcast(nai, state, type);
1191 }
1192
1193 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1194 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001195 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001196 }
1197
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001198 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001199 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001200 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1201 if (list == null || list.isEmpty()) {
1202 return;
1203 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001204 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001205
Hugo Benichi389633f2016-06-21 09:48:07 +09001206 synchronized (mTypeLists) {
1207 if (!list.remove(nai)) {
1208 return;
1209 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001210 }
1211
Lorenzo Colitti49767722015-05-01 00:30:10 +09001212 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001213 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1214 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001215 }
1216
1217 if (!list.isEmpty() && wasFirstNetwork) {
1218 if (DBG) log("Other network available for type " + type +
1219 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001220 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001221 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001222 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001223 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001224 }
1225 }
1226
1227 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001228 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1229 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001230 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001231 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001232 }
1233 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001234
Chalard Jean46bfbf02022-02-02 00:56:25 +09001235 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001236 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001237 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001238 final DetailedState state = nai.networkInfo.getDetailedState();
1239 for (int type = 0; type < mTypeLists.length; type++) {
1240 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001241 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001242 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001243 if (isFirst || contains && isDefault) {
1244 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001245 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001246 }
1247 }
1248 }
1249
Robert Greenwalt94e22142014-07-30 16:31:24 -07001250 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001251 pw.println("mLegacyTypeTracker:");
1252 pw.increaseIndent();
1253 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001254 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001255 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001256 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001257 pw.println();
1258 pw.println("Current state:");
1259 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001260 synchronized (mTypeLists) {
1261 for (int type = 0; type < mTypeLists.length; type++) {
1262 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1263 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001264 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001265 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001266 }
1267 }
1268 pw.decreaseIndent();
1269 pw.decreaseIndent();
1270 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001271 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001272 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001273 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001274
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001275 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001276 /**
1277 * Helper class which parses out priority arguments and dumps sections according to their
1278 * priority. If priority arguments are omitted, function calls the legacy dump command.
1279 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001280 private class LocalPriorityDump {
1281 private static final String PRIORITY_ARG = "--dump-priority";
1282 private static final String PRIORITY_ARG_HIGH = "HIGH";
1283 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001284 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001285
1286 LocalPriorityDump() {}
1287
1288 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001289 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> {
Junyu Laif8dba342023-10-12 17:01:03 +08001290 doDump(fd, pw, new String[]{DIAG_ARG});
1291 doDump(fd, pw, new String[]{SHORT_ARG});
1292 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1293 pw.println("dumpHigh timeout");
1294 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001295 }
1296
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001297 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001298 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> doDump(fd, pw, args),
Junyu Laif8dba342023-10-12 17:01:03 +08001299 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1300 pw.println("dumpNormal timeout");
1301 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001302 }
1303
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001304 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1305 if (args == null) {
1306 dumpNormal(fd, pw, args);
1307 return;
1308 }
1309
1310 String priority = null;
1311 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1312 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1313 argIndex++;
1314 priority = args[argIndex];
1315 }
1316 }
1317
1318 if (PRIORITY_ARG_HIGH.equals(priority)) {
1319 dumpHigh(fd, pw);
1320 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1321 dumpNormal(fd, pw, args);
1322 } else {
1323 // ConnectivityService publishes binder service using publishBinderService() with
1324 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001325 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1326 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001327 // TODO: Integrate into signal dump.
1328 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001329 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001330 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001331 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001332
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001333 /**
1334 * Dependencies of ConnectivityService, for injection in tests.
1335 */
1336 @VisibleForTesting
1337 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001338 public int getCallingUid() {
1339 return Binder.getCallingUid();
1340 }
1341
Chalard Jeandf29a852023-05-29 17:02:43 +09001342 public boolean isAtLeastS() {
1343 return SdkLevel.isAtLeastS();
1344 }
1345
1346 public boolean isAtLeastT() {
1347 return SdkLevel.isAtLeastT();
1348 }
1349
1350 public boolean isAtLeastU() {
1351 return SdkLevel.isAtLeastU();
1352 }
1353
Chalard Jeaneb663892023-10-07 15:17:07 +09001354 public boolean isAtLeastV() {
1355 return SdkLevel.isAtLeastV();
1356 }
1357
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001358 /**
1359 * Get system properties to use in ConnectivityService.
1360 */
1361 public MockableSystemProperties getSystemProperties() {
1362 return new MockableSystemProperties();
1363 }
1364
1365 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001366 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1367 */
1368 public ConnectivityResources getResources(@NonNull Context ctx) {
1369 return new ConnectivityResources(ctx);
1370 }
1371
1372 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001373 * Create a HandlerThread to use in ConnectivityService.
1374 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001375 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1376 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001377 }
1378
1379 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001380 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001381 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001382 public NetworkStackClientBase getNetworkStack() {
1383 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001384 }
1385
1386 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001387 * @see ProxyTracker
1388 */
1389 public ProxyTracker makeProxyTracker(@NonNull Context context,
1390 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001391 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001392 }
1393
1394 /**
1395 * @see NetIdManager
1396 */
1397 public NetIdManager makeNetIdManager() {
1398 return new NetIdManager();
1399 }
1400
1401 /**
1402 * @see NetworkUtils#queryUserAccess(int, int)
1403 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001404 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1405 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001406 }
1407
1408 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001409 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1410 * requires CAP_NET_ADMIN, which the unit tests do not have.
1411 */
1412 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1413 InetSocketAddress remote) {
1414 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1415 }
1416
1417 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001418 * @see MultinetworkPolicyTracker
1419 */
1420 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1421 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1422 return new MultinetworkPolicyTracker(c, h, r);
1423 }
1424
Aaron Huang330a4c02020-10-27 03:36:19 +08001425 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001426 * @see AutomaticOnOffKeepaliveTracker
1427 */
1428 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1429 @NonNull Context c, @NonNull Handler h) {
1430 return new AutomaticOnOffKeepaliveTracker(c, h);
1431 }
1432
Yang Sun29037f62023-12-04 10:31:58 +08001433 public MulticastRoutingCoordinatorService makeMulticastRoutingCoordinatorService(
1434 @NonNull Handler h) {
1435 try {
1436 return new MulticastRoutingCoordinatorService(h);
1437 } catch (UnsupportedOperationException e) {
1438 // Multicast routing is not supported by the kernel
1439 Log.i(TAG, "Skipping unsupported MulticastRoutingCoordinatorService");
1440 return null;
1441 }
1442 }
1443
chiachangwang7c17c282023-02-02 05:58:59 +00001444 /**
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001445 * @see NetworkRequestStateStatsMetrics
1446 */
1447 public NetworkRequestStateStatsMetrics makeNetworkRequestStateStatsMetrics(
1448 Context context) {
1449 // We currently have network requests metric for Watch devices only
1450 if (context.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
1451 return new NetworkRequestStateStatsMetrics();
1452 } else {
1453 return null;
1454 }
1455 }
1456
1457 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001458 * @see BatteryStatsManager
1459 */
1460 public void reportNetworkInterfaceForTransports(Context context, String iface,
1461 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001462 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001463 context.getSystemService(BatteryStatsManager.class);
1464 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1465 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001466
1467 public boolean getCellular464XlatEnabled() {
1468 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1469 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001470
1471 /**
1472 * @see PendingIntent#intentFilterEquals
1473 */
1474 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1475 return a.intentFilterEquals(b);
1476 }
1477
1478 /**
1479 * @see LocationPermissionChecker
1480 */
1481 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1482 return new LocationPermissionChecker(context);
1483 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001484
1485 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001486 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001487 *
1488 * This method returns null in versions before T, where carrier privilege
1489 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001490 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001491 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001492 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1493 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001494 if (isAtLeastT()) {
Chalard Jean96ff9542023-11-02 14:24:47 +09001495 return new CarrierPrivilegeAuthenticator(context, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001496 } else {
1497 return null;
1498 }
1499 }
1500
1501 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001502 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001503 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001504 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001505 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001506 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001507
1508 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001509 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1510 */
1511 public boolean isFeatureNotChickenedOut(Context context, String name) {
1512 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1513 }
1514
1515 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001516 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001517 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001518 * @return BpfNetMaps implementation.
1519 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001520 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1521 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001522 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001523
1524 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001525 * @see ClatCoordinator
1526 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001527 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001528 public ClatCoordinator getClatCoordinator(INetd netd) {
1529 return new ClatCoordinator(
1530 new ClatCoordinator.Dependencies() {
1531 @NonNull
1532 public INetd getNetd() {
1533 return netd;
1534 }
1535 });
1536 }
1537
1538 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001539 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1540 */
1541 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1542 final InterfaceParams params = InterfaceParams.getByName(iface);
1543 if (params == null) {
1544 // the interface might have disappeared.
1545 logw("Failed to get interface params for interface " + iface);
1546 return;
1547 }
1548 try {
1549 // converting rateInBytesPerSecond from long to int is safe here because the
1550 // setting's range is limited to INT_MAX.
1551 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001552 Log.i(TAG,
1553 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001554 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1555 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1556 } catch (IOException e) {
1557 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1558 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1559 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1560 + ") failure: ", e);
1561 }
1562 }
1563
1564 /**
1565 * Wraps {@link TcUtils#tcFilterDelDev}
1566 */
1567 public void disableIngressRateLimit(String iface) {
1568 final InterfaceParams params = InterfaceParams.getByName(iface);
1569 if (params == null) {
1570 // the interface might have disappeared.
1571 logw("Failed to get interface params for interface " + iface);
1572 return;
1573 }
1574 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001575 Log.i(TAG,
1576 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001577 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1578 } catch (IOException e) {
1579 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1580 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1581 }
1582 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001583
1584 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001585 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1586 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001587 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001588 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001589 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001590 }
1591
1592 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001593 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1594 */
1595 // TODO: when available in all active branches:
1596 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1597 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1598 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1599 return BroadcastOptionsShimImpl.newInstance(options);
1600 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001601
1602 /**
1603 * Wrapper method for
1604 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1605 *
1606 * @param changeId The ID of the compatibility change in question.
1607 * @param packageName The package name of the app in question.
1608 * @param user The user that the operation is done for.
1609 * @return {@code true} if the change is enabled for the specified package.
1610 */
1611 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1612 @NonNull final UserHandle user) {
1613 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1614 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001615
1616 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001617 * As above but with a UID.
1618 * @see CompatChanges#isChangeEnabled(long, int)
1619 */
1620 public boolean isChangeEnabled(final long changeId, final int uid) {
1621 return CompatChanges.isChangeEnabled(changeId, uid);
1622 }
1623
1624 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001625 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1626 *
1627 * @param ranges target uid ranges
1628 * @param exemptUids uids to skip close socket
1629 */
1630 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1631 @NonNull final Set<Integer> exemptUids)
1632 throws SocketException, InterruptedIOException, ErrnoException {
1633 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1634 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001635
1636 /**
1637 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1638 *
1639 * @param ownerUids target uids to close sockets
1640 */
1641 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1642 throws SocketException, InterruptedIOException, ErrnoException {
1643 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1644 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001645
1646 /**
1647 * Schedule the evaluation timeout.
1648 *
1649 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1650 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1651 * of these events happen, this time will run out, after which the network is considered
1652 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1653 * on this network and considers it won't provide connectivity. In particular, that means
1654 * it's when the system prefers it to cell if it's wifi and configuration says it should
1655 * prefer bad wifi to cell.
1656 */
1657 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1658 @NonNull final Network network, final long delayMs) {
1659 handler.sendMessageDelayed(
1660 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1661 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001662 }
1663
junyulaie7c7d2a2021-01-26 15:29:15 +08001664 public ConnectivityService(Context context) {
1665 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001666 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1667 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001668 }
1669
1670 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001671 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1672 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001673 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001674
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001675 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001676 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001677 mSystemProperties = mDeps.getSystemProperties();
1678 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001679 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001680 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001681 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1682 // Pass limit - 1 to maintain backward compatibility.
1683 // TODO: Remove the workaround.
1684 mNetworkRequestCounter =
1685 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1686 mSystemNetworkRequestCounter =
1687 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001688
Hugo Benichi208c0102016-07-28 17:53:06 +09001689 mMetricsLog = logger;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001690 mNetworkRequestStateStatsMetrics = mDeps.makeNetworkRequestStateStatsMetrics(mContext);
James Mattis45d81842021-01-10 14:24:24 -08001691 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1692 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001693 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001694 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001695 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001696 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1697 mDefaultNetworkRequests.add(mDefaultRequest);
1698 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001699
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001700 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001701 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001702
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001703 // The default WiFi request is a background request so that apps using WiFi are
1704 // migrated to a better network (typically ethernet) when one comes up, instead
1705 // of staying on WiFi forever.
1706 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1707 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1708
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001709 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1710 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1711 NetworkRequest.Type.BACKGROUND_REQUEST);
1712
Chalard Jean0702f982021-09-16 21:50:07 +09001713 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1714 // TODO: Consider making the timer customizable.
1715 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1716 mCellularRadioTimesharingCapable =
1717 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1718
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001719 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1720 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1721
1722 if (SdkLevel.isAtLeastU()) {
1723 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1724 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1725 final int defaultUMarkMask = 0x80000000; // u32
1726
1727 if ((mark == 0) || (mask == 0)) {
1728 // simply treat unset/disabled as the default U value
1729 mark = defaultUMarkMask;
1730 mask = defaultUMarkMask;
1731 }
1732 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1733 // invalid device overlay settings
1734 throw new IllegalArgumentException(
1735 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1736 }
1737 }
1738
1739 mWakeUpMark = mark;
1740 mWakeUpMask = mask;
1741
Paul Hu51f816b2022-08-11 14:43:47 +00001742 mNetd = netd;
1743 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09001744 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00001745 mPermissionMonitor =
1746 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001747 mHandlerThread.start();
1748 mHandler = new InternalHandler(mHandlerThread.getLooper());
1749 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001750 mConnectivityDiagnosticsHandler =
1751 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001752
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001753 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001754 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001755
junyulaie7c7d2a2021-01-26 15:29:15 +08001756 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001757 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001758 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001759 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001760
Wink Saville32506bc2013-06-29 21:10:57 -07001761 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001762 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001763 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001764 mCarrierPrivilegeAuthenticator =
1765 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001766
Sudheer Shanka9967d462021-03-18 19:09:25 +00001767 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001768 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1769 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001770 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001771
1772 final PowerManager powerManager = (PowerManager) context.getSystemService(
1773 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001774 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001775 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001776
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001777 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1778 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001779 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001780 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001781 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001782 mProtectedNetworks.add(p);
1783 } else {
1784 if (DBG) loge("Ignoring protectedNetwork " + p);
1785 }
1786 }
1787
soma, kawata29444ae2019-05-23 09:30:40 +09001788 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1789
James Mattis02220e22021-03-13 19:27:21 -08001790 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001791 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001792 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001793 final IntentFilter userIntentFilter = new IntentFilter();
1794 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1795 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1796 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1797 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001798
James Mattis02220e22021-03-13 19:27:21 -08001799 // Listen to package add/removes for netd
1800 final IntentFilter packageIntentFilter = new IntentFilter();
1801 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1802 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1803 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1804 packageIntentFilter.addDataScheme("package");
1805 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001806 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001807
Junyu Lai38c75032023-12-04 07:52:19 +00001808 // This is needed for pre-V devices to propagate the data saver status
1809 // to the BPF map. This isn't supported before Android T because BPF maps are
1810 // unsupported, and it's also unnecessary on Android V and later versions,
1811 // as the platform code handles data saver bit updates. Additionally, checking
1812 // the initial data saver status here is superfluous because the intent won't
1813 // be sent until the system is ready.
1814 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
1815 final IntentFilter dataSaverIntentFilter =
1816 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
1817 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
1818 null /* broadcastPermission */, mHandler);
1819 }
1820
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001821 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1822 // But reading the trunk stable flags from mainline modules is not supported yet.
1823 // So enabling this feature on V+ release.
1824 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1825 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1826 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001827
Chalard Jean46bfbf02022-02-02 00:56:25 +09001828 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001829 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001830 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001831 } catch (RemoteException | ServiceSpecificException e) {
1832 loge("Error registering event listener :" + e);
1833 }
1834
Erik Kline05f2b402015-04-30 12:58:40 +09001835 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1836 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001837
chiachangwang7c17c282023-02-02 05:58:59 +00001838 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001839 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001840 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001841
1842 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001843 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001844 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1845 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001846 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001847 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1848 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001849
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001850 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001851 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001852 mNetworkRanker =
1853 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1854
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001855 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001856
Chiachang Wangc1215d32020-10-20 15:38:58 +08001857 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001858 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001859
Chalard Jean28018572020-12-21 18:36:52 +09001860 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1861 // request that doesn't allow fallback to the default network. It should never be visible
1862 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1863 // arguments like the handler or the DnsResolver.
1864 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001865 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001866 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001867 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001868 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001869 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001870 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1871 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001872
1873 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001874 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1875 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1876 // Even if it could, running on S would at least require mocking out the BPF map,
1877 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1878 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001879 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001880 mDscpPolicyTracker = new DscpPolicyTracker();
1881 }
Tyler Wear72388212021-09-09 14:49:02 -07001882 } catch (ErrnoException e) {
1883 loge("Unable to create DscpPolicyTracker");
1884 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001885
1886 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1887 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001888
Chalard Jeandf29a852023-05-29 17:02:43 +09001889 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001890 mCdmps = new CompanionDeviceManagerProxyService(context);
1891 } else {
1892 mCdmps = null;
1893 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001894
Chalard Jean2fb66f12023-08-25 12:50:37 +09001895 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
Yang Sun29037f62023-12-04 10:31:58 +08001896 mMulticastRoutingCoordinatorService =
1897 mDeps.makeMulticastRoutingCoordinatorService(mHandler);
Chalard Jean2fb66f12023-08-25 12:50:37 +09001898
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001899 mDestroyFrozenSockets = mDeps.isAtLeastU()
1900 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1901 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1902 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001903 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1904 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001905 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001906 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1907 new UidFrozenStateChangedCallback() {
1908 @Override
1909 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1910 if (uids.length != frozenStates.length) {
1911 Log.wtf(TAG, "uids has length " + uids.length
1912 + " but frozenStates has length " + frozenStates.length);
1913 return;
1914 }
1915
1916 final UidFrozenStateChangedArgs args =
1917 new UidFrozenStateChangedArgs(uids, frozenStates);
1918
1919 mHandler.sendMessage(
1920 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1921 }
1922 };
1923
1924 final ActivityManager activityManager =
1925 mContext.getSystemService(ActivityManager.class);
1926 activityManager.registerUidFrozenStateChangedCallback(
1927 (Runnable r) -> r.run(), frozenStateChangedCallback);
1928 }
Yuyang Huang41557552023-11-28 12:47:22 +09001929
1930 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
1931 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
1932 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001933 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001934
Xiao Ma0a171c02022-01-23 16:14:51 +00001935 /**
1936 * Check whether or not the device supports Ethernet transport.
1937 */
1938 public static boolean deviceSupportsEthernet(final Context context) {
1939 final PackageManager pm = context.getPackageManager();
1940 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1941 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1942 }
1943
Chalard Jean46adcf32018-04-18 20:18:38 +09001944 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001945 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1946 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001947 }
1948
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001949 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1950 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001951 final NetworkCapabilities netCap = new NetworkCapabilities();
1952 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001953 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001954 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001955 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001956 return netCap;
1957 }
1958
James Mattis45d81842021-01-10 14:24:24 -08001959 private NetworkRequest createDefaultRequest() {
1960 return createDefaultInternetRequestForTransport(
1961 TYPE_NONE, NetworkRequest.Type.REQUEST);
1962 }
1963
lucaslin3ba7cc22022-12-19 02:35:33 +00001964 private NetworkRequest createVpnRequest() {
1965 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1966 .withoutDefaultCapabilities()
1967 .addTransportType(TRANSPORT_VPN)
1968 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1969 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1970 .build();
1971 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1972 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1973 }
1974
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001975 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001976 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001977 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001978 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001979 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001980 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001981 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001982 netCap.addTransportType(transportType);
1983 }
James Mattis45d81842021-01-10 14:24:24 -08001984 return createNetworkRequest(type, netCap);
1985 }
1986
1987 private NetworkRequest createNetworkRequest(
1988 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001989 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001990 }
1991
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001992 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1993 NetworkRequest.Type type) {
1994 final NetworkCapabilities netCap = new NetworkCapabilities();
1995 netCap.clearAll();
1996 netCap.addCapability(capability);
1997 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1998 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1999 }
2000
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002001 // Used only for testing.
2002 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07002003 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002004 // changing ContentResolver to make registerContentObserver non-final).
2005 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
2006 // by subclassing SettingsObserver.
2007 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002008 void updateAlwaysOnNetworks() {
2009 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002010 }
2011
Erik Kline9a62f012018-03-21 07:18:33 -07002012 // See FakeSettingsProvider comment above.
2013 @VisibleForTesting
2014 void updatePrivateDnsSettings() {
2015 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
2016 }
2017
paulhu51f77dc2021-06-07 02:34:20 +00002018 @VisibleForTesting
2019 void updateMobileDataPreferredUids() {
2020 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
2021 }
2022
Patrick Rohr2857ac42022-01-21 14:58:16 +01002023 @VisibleForTesting
2024 void updateIngressRateLimit() {
2025 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
2026 }
2027
Aaron Huang40b52442021-06-08 04:34:24 +08002028 @VisibleForTesting
2029 void simulateUpdateProxyInfo(@Nullable final Network network,
2030 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08002031 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08002032 new Pair<>(network, proxyInfo)).sendToTarget();
2033 }
2034
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002035 private void handleAlwaysOnNetworkRequest(
2036 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002037 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002038 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002039 handleAlwaysOnNetworkRequest(networkRequest, enable);
2040 }
2041
2042 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002043 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002044 if (enable == isEnabled) {
2045 return; // Nothing to do.
2046 }
2047
2048 if (enable) {
2049 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002050 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002051 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002052 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002053 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002054 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2055 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002056 }
2057 }
2058
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002059 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002060 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2061 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2062 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2063 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002064 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2065 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002066 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002067 }
2068
paulhu51f77dc2021-06-07 02:34:20 +00002069 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002070 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002071 private void registerSettingsCallbacks() {
2072 // Watch for global HTTP proxy changes.
2073 mSettingsObserver.observe(
2074 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2075 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2076
Chalard Jean46bfbf02022-02-02 00:56:25 +09002077 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002078 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002079 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002080 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2081
Chalard Jean46bfbf02022-02-02 00:56:25 +09002082 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002083 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002084 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002085 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002086
2087 // Watch for mobile data preferred uids changes.
2088 mSettingsObserver.observe(
2089 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2090 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002091
2092 // Watch for ingress rate limit changes.
2093 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002094 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002095 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2096 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002097 }
2098
Erik Kline31b4a9e2018-01-11 21:07:29 +09002099 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002100 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2101 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002102 }
2103 }
2104
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002105 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002106 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2107 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002108 return mNextNetworkRequestId++;
2109 }
2110
junyulai74f9a8b2018-06-13 15:00:37 +08002111 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002112 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002113 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002114 if (network == null) {
2115 return null;
2116 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002117 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002118 }
2119
2120 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002121 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002122 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002123 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002124 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002125
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002126 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002127 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002128 private NetworkAgentInfo getVpnForUid(int uid) {
2129 synchronized (mNetworkForNetId) {
2130 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2131 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002132 if (nai.isVPN() && nai.everConnected()
2133 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002134 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002135 }
2136 }
2137 }
2138 return null;
2139 }
2140
Chalard Jean46bfbf02022-02-02 00:56:25 +09002141 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002142 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002143 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002144 final NetworkAgentInfo nai = getVpnForUid(uid);
2145 if (nai != null) return nai.declaredUnderlyingNetworks;
2146 return null;
2147 }
2148
Lorenzo Colittia7574052021-01-19 01:33:05 +09002149 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002150 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002151
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002152 final Network[] networks = getVpnUnderlyingNetworks(uid);
2153 if (networks != null) {
2154 // getUnderlyingNetworks() returns:
2155 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2156 // empty array => the VPN explicitly said "no default network".
2157 // non-empty array => the VPN specified one or more default networks; we use the
2158 // first one.
2159 if (networks.length > 0) {
2160 nai = getNetworkAgentInfoForNetwork(networks[0]);
2161 } else {
2162 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002163 }
2164 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002165 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002166 }
2167
2168 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002169 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002170 */
paulhu7aeba372020-12-30 00:42:19 +08002171 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2172 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002173 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002174 if (ignoreBlocked) {
2175 return false;
2176 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002177 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002178 final long ident = Binder.clearCallingIdentity();
2179 try {
2180 final boolean metered = nc == null ? true : nc.isMetered();
2181 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2182 } finally {
2183 Binder.restoreCallingIdentity(ident);
2184 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002185 }
2186
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002187 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002188 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2189 return;
2190 }
Hugo Benichi47011212017-03-30 10:46:05 +09002191 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002192 synchronized (mBlockedAppUids) {
2193 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002194 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002195 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002196 blocked = false;
2197 } else {
2198 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002199 }
2200 }
Hugo Benichi47011212017-03-30 10:46:05 +09002201 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2202 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2203 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002204 }
2205
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002206 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002207 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2208 return;
2209 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002210 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002211 final int requestId = nri.getActiveRequest() != null
2212 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002213 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002214 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002215 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002216 }
2217
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002218 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002219 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002220 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002221 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002222 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002223 @NonNull
2224 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2225 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002226 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2227 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2228 // but only exists if an app asks about them or requests them. Ensure the requesting app
2229 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002230 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002231 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2232 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2233 null /* extraInfo */);
2234 }
2235 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002236 return filtered;
2237 }
2238
2239 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2240 boolean ignoreBlocked) {
2241 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2242 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002243 }
2244
2245 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002246 * Return NetworkInfo for the active (i.e., connected) network interface.
2247 * It is assumed that at most one network is active at a time. If more
2248 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002249 * @return the info for the active network, or {@code null} if none is
2250 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002251 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002252 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002253 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002254 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002255 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002256 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002257 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2258 if (nai == null) return null;
2259 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2260 maybeLogBlockedNetworkInfo(networkInfo, uid);
2261 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002262 }
2263
Paul Jensen1f567382015-02-13 14:18:39 -05002264 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002265 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002266 public Network getActiveNetwork() {
2267 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002268 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002269 }
2270
2271 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002272 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002273 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002274 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002275 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002276 }
2277
Chalard Jean46bfbf02022-02-02 00:56:25 +09002278 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002279 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002280 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2281 if (vpnNai != null) {
2282 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2283 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2284 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002285 }
Paul Jensen1f567382015-02-13 14:18:39 -05002286 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002287
James Mattis2516da32021-01-31 17:06:19 -08002288 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002289 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2290 ignoreBlocked)) {
2291 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002292 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002293 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002294 }
2295
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002296 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002297 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002298 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002299 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002300 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2301 if (nai == null) return null;
2302 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002303 }
2304
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002305 /** Returns a NetworkInfo object for a network that doesn't exist. */
2306 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2307 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2308 getNetworkTypeName(networkType), "" /* subtypeName */);
2309 info.setIsAvailable(true);
2310 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2311 // background data is restricted.
2312 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2313 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2314 ? DetailedState.BLOCKED
2315 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002316 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2317 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002318 return info;
2319 }
2320
Lorenzo Colittia7574052021-01-19 01:33:05 +09002321 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002322 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2323 return null;
2324 }
2325 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002326 if (nai == null) {
2327 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002328 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002329 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2330 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002331 }
2332
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002333 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002334 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002335 public NetworkInfo getNetworkInfo(int networkType) {
2336 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002337 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002338 if (getVpnUnderlyingNetworks(uid) != null) {
2339 // A VPN is active, so we may need to return one of its underlying networks. This
2340 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002341 // getNetworkAgentInfoForUid.
2342 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2343 if (nai == null) return null;
2344 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2345 if (networkInfo.getType() == networkType) {
2346 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002347 }
2348 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002349 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002350 }
2351
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002352 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002353 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002354 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002355 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002356 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002357 if (nai == null) return null;
2358 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002359 }
2360
2361 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002362 public NetworkInfo[] getAllNetworkInfo() {
2363 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002364 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002365 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2366 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002367 NetworkInfo info = getNetworkInfo(networkType);
2368 if (info != null) {
2369 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002370 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002371 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002372 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002373 }
2374
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002375 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002376 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002377 public Network getNetworkForType(int networkType) {
2378 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002379 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2380 return null;
2381 }
2382 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2383 if (nai == null) {
2384 return null;
2385 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002386 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002387 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2388 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002389 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002390 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002391 }
2392
2393 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002394 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002395 public Network[] getAllNetworks() {
2396 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002397 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002398 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002399 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002400 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002401 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002402 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002403 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002404 }
2405
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002406 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002407 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002408 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002409 // The basic principle is: if an app's traffic could possibly go over a
2410 // network, without the app doing anything multinetwork-specific,
2411 // (hence, by "default"), then include that network's capabilities in
2412 // the array.
2413 //
2414 // In the normal case, app traffic only goes over the system's default
2415 // network connection, so that's the only network returned.
2416 //
2417 // With a VPN in force, some app traffic may go into the VPN, and thus
2418 // over whatever underlying networks the VPN specifies, while other app
2419 // traffic may go over the system default network (e.g.: a split-tunnel
2420 // VPN, or an app disallowed by the VPN), so the set of networks
2421 // returned includes the VPN's underlying networks and the system
2422 // default.
2423 enforceAccessPermission();
2424
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002425 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002426
James Mattis2516da32021-01-31 17:06:19 -08002427 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2428 if (!nri.isBeingSatisfied()) {
2429 continue;
2430 }
2431 final NetworkAgentInfo nai = nri.getSatisfier();
2432 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2433 if (null != nc
2434 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2435 && !result.containsKey(nai.network)) {
2436 result.put(
2437 nai.network,
2438 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002439 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002440 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2441 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002442 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002443 }
2444
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002445 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002446 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002447 if (null != networks) {
2448 for (final Network network : networks) {
2449 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2450 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002451 result.put(
2452 network,
2453 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002454 nc,
2455 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002456 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002457 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002458 }
2459 }
2460 }
2461
2462 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2463 out = result.values().toArray(out);
2464 return out;
2465 }
2466
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002467 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2468 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2469 // can call sampleConnectivityState and make the checks on it.
2470 @NonNull
2471 private StatsEvent sampleConnectivityStateToStatsEvent() {
2472 final ConnectivityStateSample sample = sampleConnectivityState();
2473 return ConnectivityStatsLog.buildStatsEvent(
2474 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2475 sample.getNetworkCountPerTransports().toByteArray(),
2476 sample.getConnectionDurationPerTransports().toByteArray(),
2477 sample.getNetworkRequestCount().toByteArray(),
2478 sample.getNetworks().toByteArray());
2479 }
2480
2481 /**
2482 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2483 *
2484 * This is used for metrics. These snapshots will be sampled and constitute a base for
2485 * statistics about connectivity state of devices.
2486 */
2487 @VisibleForTesting
2488 @NonNull
2489 public ConnectivityStateSample sampleConnectivityState() {
2490 ensureRunningOnConnectivityServiceThread();
2491 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2492 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2493 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2494 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2495 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2496 return builder.build();
2497 }
2498
2499 private static NetworkCountPerTransports sampleNetworkCount(
2500 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2501 final SparseIntArray countPerTransports = new SparseIntArray();
2502 for (final NetworkAgentInfo nai : nais) {
2503 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2504 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2505 }
2506 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2507 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2508 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2509 c.setTransportTypes(countPerTransports.keyAt(i));
2510 c.setNetworkCount(countPerTransports.valueAt(i));
2511 builder.addNetworkCountForTransports(c);
2512 }
2513 return builder.build();
2514 }
2515
2516 private static ConnectionDurationPerTransports sampleConnectionDuration(
2517 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2518 final ConnectionDurationPerTransports.Builder builder =
2519 ConnectionDurationPerTransports.newBuilder();
2520 for (final NetworkAgentInfo nai : nais) {
2521 final ConnectionDurationForTransports.Builder c =
2522 ConnectionDurationForTransports.newBuilder();
2523 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2524 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2525 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2526 // Add millisPerSecond/2 to round up or down to the nearest value
2527 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2528 builder.addConnectionDurationForTransports(c);
2529 }
2530 return builder.build();
2531 }
2532
2533 private static NetworkRequestCount sampleNetworkRequestCount(
2534 @NonNull final Collection<NetworkRequestInfo> nris) {
2535 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2536 final SparseIntArray countPerType = new SparseIntArray();
2537 for (final NetworkRequestInfo nri : nris) {
2538 final int type;
2539 if (Process.SYSTEM_UID == nri.mAsUid) {
2540 // The request is filed "as" the system, so it's the system on its own behalf.
2541 type = RequestType.RT_SYSTEM.getNumber();
2542 } else if (Process.SYSTEM_UID == nri.mUid) {
2543 // The request is filed by the system as some other app, so it's the system on
2544 // behalf of an app.
2545 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2546 } else {
2547 // Not the system, so it's an app requesting on its own behalf.
2548 type = RequestType.RT_APP.getNumber();
2549 }
2550 countPerType.put(type, countPerType.get(type, 0));
2551 }
2552 for (int i = countPerType.size() - 1; i >= 0; --i) {
2553 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2554 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2555 r.setRequestCount(countPerType.valueAt(i));
2556 builder.addRequestCountForType(r);
2557 }
2558 return builder.build();
2559 }
2560
2561 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2562 final NetworkList.Builder builder = NetworkList.newBuilder();
2563 for (final NetworkAgentInfo nai : nais) {
2564 final NetworkCapabilities nc = nai.networkCapabilities;
2565 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2566 d.setTransportTypes((int) nc.getTransportTypesInternal());
2567 final MeteredState meteredState;
2568 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2569 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2570 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2571 meteredState = MeteredState.METERED_NO;
2572 } else {
2573 meteredState = MeteredState.METERED_YES;
2574 }
2575 d.setMeteredState(meteredState);
2576 final ValidatedState validatedState;
2577 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2578 validatedState = ValidatedState.VS_PORTAL;
2579 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2580 validatedState = ValidatedState.VS_PARTIAL;
2581 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2582 validatedState = ValidatedState.VS_VALID;
2583 } else {
2584 validatedState = ValidatedState.VS_INVALID;
2585 }
2586 d.setValidatedState(validatedState);
2587 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2588 d.setCapabilities(nc.getCapabilitiesInternal());
2589 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2590 builder.addNetworkDescription(d);
2591 }
2592 return builder.build();
2593 }
2594
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002595 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002596 public boolean isNetworkSupported(int networkType) {
2597 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002598 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002599 }
2600
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002601 /**
2602 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002603 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002604 * @return the ip properties for the active network, or {@code null} if
2605 * none is active
2606 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002607 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002608 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002609 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002610 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002611 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2612 if (nai == null) return null;
2613 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002614 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002615 }
2616
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002617 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002618 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002619 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002620 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002621 final LinkProperties lp = getLinkProperties(nai);
2622 if (lp == null) return null;
2623 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002624 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002625 }
2626
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002627 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002628 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002629 public LinkProperties getLinkProperties(Network network) {
2630 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002631 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2632 if (lp == null) return null;
2633 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002634 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002635 }
2636
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002637 @Nullable
2638 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002639 if (nai == null) {
2640 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002641 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002642 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002643 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002644 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002645 }
2646
lucaslinc582d502022-01-27 09:07:00 +08002647 @Override
2648 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002649 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002650 @NonNull String packageName, @Nullable String callingAttributionTag) {
2651 Objects.requireNonNull(packageName);
2652 Objects.requireNonNull(lp);
2653 enforceNetworkStackOrSettingsPermission();
2654 if (!checkAccessPermission(-1 /* pid */, uid)) {
2655 return null;
2656 }
2657 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2658 }
2659
Qingxi Lib2748102020-01-08 12:51:49 -08002660 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2661 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2662 }
2663
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002664 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002665 if (nai == null) return null;
2666 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002667 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002668 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002669 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002670 }
2671
2672 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002673 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2674 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002675 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002676 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002677 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002678 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002679 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002680 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002681 }
2682
lucaslinc582d502022-01-27 09:07:00 +08002683 @Override
lucaslind2b06132022-03-02 10:56:57 +08002684 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2685 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2686 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002687 Objects.requireNonNull(nc);
2688 Objects.requireNonNull(packageName);
2689 enforceNetworkStackOrSettingsPermission();
2690 if (!checkAccessPermission(-1 /* pid */, uid)) {
2691 return null;
2692 }
2693 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2694 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2695 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2696 callingAttributionTag);
2697 }
2698
lucaslin69e1aa92022-03-22 18:15:09 +08002699 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2700 if (nc.getUnderlyingNetworks() != null
2701 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2702 nc.setUnderlyingNetworks(null);
2703 }
2704 }
2705
Chalard Jean53017782022-11-24 17:13:44 +09002706 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
2707 return Process.SYSTEM_UID == uid
Chalard Jean53017782022-11-24 17:13:44 +09002708 || checkAnyPermissionOf(mContext, pid, uid,
2709 android.Manifest.permission.NETWORK_FACTORY);
2710 }
2711
Qingxi Libb8da982020-01-17 17:54:27 -08002712 @VisibleForTesting
2713 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002714 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002715 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2716 // this would be expensive (one more permission check every time any NC callback is
2717 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2718 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2719 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002720 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002721 if (!checkSettingsPermission(callerPid, callerUid)) {
2722 newNc.setUids(null);
2723 newNc.setSSID(null);
2724 }
Etan Cohen107ae952018-12-30 17:59:59 -08002725 if (newNc.getNetworkSpecifier() != null) {
2726 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2727 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002728 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2729 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002730 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2731 newNc.setAdministratorUids(new int[0]);
2732 }
Chalard Jean53017782022-11-24 17:13:44 +09002733 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09002734 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002735 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002736 }
lucaslin69e1aa92022-03-22 18:15:09 +08002737 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002738
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002739 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002740 }
2741
Roshan Pius98f59ec2021-02-23 08:47:39 -08002742 /**
2743 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002744 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002745 * NetworkCapabilities.
2746 * Note: This wrapper does not support any sort of invalidation and thus must not be
2747 * persistent or long-lived. It may only be used for the time necessary to
2748 * compute the redactions required by one particular NetworkCallback or
2749 * synchronous call.
2750 */
2751 private class RedactionPermissionChecker {
2752 private final int mCallingPid;
2753 private final int mCallingUid;
2754 @NonNull private final String mCallingPackageName;
2755 @Nullable private final String mCallingAttributionTag;
2756
2757 private Boolean mHasLocationPermission = null;
2758 private Boolean mHasLocalMacAddressPermission = null;
2759 private Boolean mHasSettingsPermission = null;
2760
2761 RedactionPermissionChecker(int callingPid, int callingUid,
2762 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2763 mCallingPid = callingPid;
2764 mCallingUid = callingUid;
2765 mCallingPackageName = callingPackageName;
2766 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002767 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002768
2769 private boolean hasLocationPermissionInternal() {
2770 final long token = Binder.clearCallingIdentity();
2771 try {
2772 return mLocationPermissionChecker.checkLocationPermission(
2773 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2774 null /* message */);
2775 } finally {
2776 Binder.restoreCallingIdentity(token);
2777 }
2778 }
2779
2780 /**
2781 * Returns whether the app holds location permission or not (might return cached result
2782 * if the permission was already checked before).
2783 */
2784 public boolean hasLocationPermission() {
2785 if (mHasLocationPermission == null) {
2786 // If there is no cached result, perform the check now.
2787 mHasLocationPermission = hasLocationPermissionInternal();
2788 }
2789 return mHasLocationPermission;
2790 }
2791
2792 /**
2793 * Returns whether the app holds local mac address permission or not (might return cached
2794 * result if the permission was already checked before).
2795 */
2796 public boolean hasLocalMacAddressPermission() {
2797 if (mHasLocalMacAddressPermission == null) {
2798 // If there is no cached result, perform the check now.
2799 mHasLocalMacAddressPermission =
2800 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2801 }
2802 return mHasLocalMacAddressPermission;
2803 }
2804
2805 /**
2806 * Returns whether the app holds settings permission or not (might return cached
2807 * result if the permission was already checked before).
2808 */
2809 public boolean hasSettingsPermission() {
2810 if (mHasSettingsPermission == null) {
2811 // If there is no cached result, perform the check now.
2812 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2813 }
2814 return mHasSettingsPermission;
2815 }
2816 }
2817
2818 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2819 @NetworkCapabilities.NetCapability long redaction) {
2820 return (redactions & redaction) != 0;
2821 }
2822
2823 /**
2824 * Use the provided |applicableRedactions| to check the receiving app's
2825 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2826 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2827 * before being sent to the corresponding app.
2828 */
2829 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2830 @NetworkCapabilities.RedactionType long applicableRedactions,
2831 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2832 boolean includeLocationSensitiveInfo) {
2833 long redactions = applicableRedactions;
2834 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2835 if (includeLocationSensitiveInfo
2836 && redactionPermissionChecker.hasLocationPermission()) {
2837 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2838 }
2839 }
2840 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2841 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2842 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2843 }
2844 }
2845 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2846 if (redactionPermissionChecker.hasSettingsPermission()) {
2847 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2848 }
2849 }
2850 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002851 }
2852
Qingxi Lib2748102020-01-08 12:51:49 -08002853 @VisibleForTesting
2854 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002855 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002856 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002857 int callingPid, int callingUid, @NonNull String callingPkgName,
2858 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002859 if (nc == null) {
2860 return null;
2861 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002862 // Avoid doing location permission check if the transport info has no location sensitive
2863 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002864 final RedactionPermissionChecker redactionPermissionChecker =
2865 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2866 callingAttributionTag);
2867 final long redactions = retrieveRequiredRedactions(
2868 nc.getApplicableRedactions(), redactionPermissionChecker,
2869 includeLocationSensitiveInfo);
2870 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002871 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002872 // TODO : calling UID is redacted because apps should generally not know what UID is
2873 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002874 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002875 newNc.setOwnerUid(INVALID_UID);
2876 return newNc;
2877 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002878 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2879 if (nc.hasTransport(TRANSPORT_VPN)) {
2880 // Owner UIDs already checked above. No need to re-check.
2881 return newNc;
2882 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002883 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2884 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002885 // compatibility for older apps.
2886 if (!includeLocationSensitiveInfo
2887 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002888 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002889 newNc.setOwnerUid(INVALID_UID);
2890 return newNc;
2891 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002892 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002893 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002894 newNc.setOwnerUid(INVALID_UID);
2895 }
Qingxi Lib2748102020-01-08 12:51:49 -08002896 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002897 }
2898
lucaslinc582d502022-01-27 09:07:00 +08002899 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002900 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2901 LinkProperties lp, int callerPid, int callerUid) {
2902 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002903 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2904 // this would be expensive (one more permission check every time any LP callback is
2905 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2906 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2907 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002908
2909 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2910 final boolean needsSanitization =
2911 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2912 if (!needsSanitization) {
2913 return new LinkProperties(lp);
2914 }
2915
2916 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002917 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002918 }
2919
2920 final LinkProperties newLp = new LinkProperties(lp);
2921 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2922 // object gets parceled.
2923 newLp.setCaptivePortalApiUrl(null);
2924 newLp.setCaptivePortalData(null);
2925 return newLp;
2926 }
2927
Roshan Pius08c94fb2020-01-16 12:17:17 -08002928 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2929 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002930 // There is no need to track the effective UID of the request here. If the caller
2931 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002932 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002933 // Unprivileged apps can only pass in null or their own UID.
2934 if (nc.getUids() == null) {
2935 // If the caller passes in null, the callback will also match networks that do not
2936 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2937 // In this case, redact everything in the request immediately. This ensures that the
2938 // app is not able to get any redacted information by filing an unredacted request
2939 // and observing whether the request matches something.
2940 if (nc.getNetworkSpecifier() != null) {
2941 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2942 }
2943 } else {
2944 nc.setSingleUid(callerUid);
2945 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002946 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002947 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002948 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002949
2950 // Clear owner UID; this can never come from an app.
2951 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002952 }
2953
Chalard Jean38354d12018-03-20 19:13:57 +09002954 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002955 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002956 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2957 }
2958 }
2959
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002960 @Override
2961 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2962 enforceAccessPermission();
2963 final int callerUid = Binder.getCallingUid();
2964 final long token = Binder.clearCallingIdentity();
2965 try {
2966 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2967 } finally {
2968 Binder.restoreCallingIdentity(token);
2969 }
2970 }
2971
junyulaiebd15162021-03-03 12:09:05 +08002972 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002973 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002974 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002975 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002976 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002977
Serik Beketayev05130302021-01-15 16:47:25 -08002978 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002979 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002980 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2981 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002982 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002983 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002984 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002985 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2986 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002987 }
2988 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002989 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002990 }
2991
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002992 @Override
junyulaiebd15162021-03-03 12:09:05 +08002993 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002994 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002995 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002996 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002997
2998 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2999 for (Network network : getAllNetworks()) {
3000 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09003001 final boolean includeNetwork = (nai != null) && nai.isCreated();
3002 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08003003 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
3004 // NetworkCapabilities, which may contain UIDs of apps to which the
3005 // network applies. Should the UIDs be cleared so as not to leak or
3006 // interfere ?
3007 result.add(nai.getNetworkStateSnapshot());
3008 }
3009 }
3010 return result;
3011 }
3012
3013 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003014 public boolean isActiveNetworkMetered() {
3015 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003016
Qingxi Lib2748102020-01-08 12:51:49 -08003017 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06003018 if (caps != null) {
3019 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3020 } else {
3021 // Always return the most conservative value
3022 return true;
3023 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07003024 }
3025
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003026 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09003027 * Ensures that the system cannot call a particular method.
3028 */
3029 private boolean disallowedBecauseSystemCaller() {
3030 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07003031 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
3032 // for devices launched with Q and above. However, existing devices upgrading to Q and
3033 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003034 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07003035 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003036 log("This method exists only for app backwards compatibility"
3037 + " and must not be called by system services.");
3038 return true;
3039 }
3040 return false;
3041 }
3042
3043 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003044 * Ensure that a network route exists to deliver traffic to the specified
3045 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003046 * @param networkType the type of the network over which traffic to the
3047 * specified host is to be routed
3048 * @param hostAddress the IP address of the host to which the route is
3049 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003050 * @return {@code true} on success, {@code false} on failure
3051 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003052 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003053 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3054 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003055 if (disallowedBecauseSystemCaller()) {
3056 return false;
3057 }
Junyu Lai8fdc4312024-01-16 11:19:43 +08003058 PermissionUtils.enforcePackageNameMatchesUid(
3059 mContext, mDeps.getCallingUid(), callingPackageName);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003060 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003061 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003062 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003063 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003064
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003065 InetAddress addr;
3066 try {
3067 addr = InetAddress.getByAddress(hostAddress);
3068 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003069 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003070 return false;
3071 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003072
The Android Open Source Project28527d22009-03-03 19:31:44 -08003073 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003074 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003075 return false;
3076 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003077
3078 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3079 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003080 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003081 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3082 } else {
3083 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3084 }
3085 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003086 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003087
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003088 DetailedState netState;
3089 synchronized (nai) {
3090 netState = nai.networkInfo.getDetailedState();
3091 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003092
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003093 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003094 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003095 log("requestRouteToHostAddress on down network "
3096 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003097 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003098 }
3099 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003100 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003101
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003102 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003103 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003104 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003105 LinkProperties lp;
3106 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003107 synchronized (nai) {
3108 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003109 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003110 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003111 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003112 if (DBG) {
3113 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3114 }
Wink Saville32506bc2013-06-29 21:10:57 -07003115 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003116 } finally {
3117 Binder.restoreCallingIdentity(token);
3118 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003119 }
3120
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003121 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003122 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003123 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003124 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003125 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003126 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003127 if (bestRoute.getGateway().equals(addr)) {
3128 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003129 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003130 } else {
3131 // if we will connect to this through another route, add a direct route
3132 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003133 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003134 }
3135 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003136 if (DBG) log("Adding legacy route " + bestRoute +
3137 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003138
3139 final String dst = bestRoute.getDestinationLinkAddress().toString();
3140 final String nextHop = bestRoute.hasGateway()
3141 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003142 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003143 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3144 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003145 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003146 return false;
3147 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003148 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003149 }
3150
paulhu7c0a2e62021-01-08 00:51:49 +08003151 class DnsResolverUnsolicitedEventCallback extends
3152 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003153 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003154 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003155 try {
3156 mHandler.sendMessage(mHandler.obtainMessage(
3157 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003158 new PrivateDnsValidationUpdate(event.netId,
3159 InetAddresses.parseNumericAddress(event.ipAddress),
3160 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003161 } catch (IllegalArgumentException e) {
3162 loge("Error parsing ip address in validation event");
3163 }
3164 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003165
3166 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003167 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3168 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003169 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3170 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3171 // event callback for certain nai. e.g. cellular. Register here to pass to
3172 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003173 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003174 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3175 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003176 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003177 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003178 }
3179 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003180
3181 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003182 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3183 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3184 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003185 }
dalyk1720e542018-03-05 12:42:22 -05003186
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003187 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003188 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003189 return this.VERSION;
3190 }
3191
3192 @Override
3193 public String getInterfaceHash() {
3194 return this.HASH;
3195 }
paulhu7c0a2e62021-01-08 00:51:49 +08003196 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003197
3198 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003199 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3200 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003201
paulhu7c0a2e62021-01-08 00:51:49 +08003202 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003203 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003204 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003205 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003206 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003207 }
3208 }
3209
Sudheer Shanka9967d462021-03-18 19:09:25 +00003210 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003211 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003212 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003213 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3214 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003215 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003216 };
3217
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003218 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003219 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003220 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003221 }
3222
Mark Fasheh7c999d82023-05-04 20:23:11 +00003223 static final class UidFrozenStateChangedArgs {
3224 final int[] mUids;
3225 final int[] mFrozenStates;
3226
3227 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3228 mUids = uids;
3229 mFrozenStates = frozenStates;
3230 }
3231 }
3232
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003233 /**
3234 * Check if the cell network is idle.
3235 * @return true if the cell network state is idle
3236 * false if the cell network state is active or unknown
3237 */
3238 private boolean isCellNetworkIdle() {
3239 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3240 if (defaultNai == null
3241 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3242 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3243 // cell network is not the default network, cell network state is unknown.
3244 // TODO(b/279380356): Track cell network state when the cell is not the default network
3245 return false;
3246 }
3247
3248 return !mNetworkActivityTracker.isDefaultNetworkActive();
3249 }
3250
Mark Fasheh7c999d82023-05-04 20:23:11 +00003251 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003252 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003253
3254 for (int i = 0; i < uids.length; i++) {
3255 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003256 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003257 } else {
3258 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003259 }
3260 }
3261
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003262 if (ownerUids.isEmpty()) {
3263 return;
3264 }
3265
3266 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3267 // Delay closing sockets to avoid waking the cell modem up.
3268 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3269 // than waking cell modem up.
3270 mPendingFrozenUids.addAll(ownerUids);
3271 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003272 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003273 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003274 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003275 loge("Exception in socket destroy: " + e);
3276 }
3277 }
3278 }
3279
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003280 private void closePendingFrozenSockets() {
3281 ensureRunningOnConnectivityServiceThread();
3282
3283 try {
3284 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3285 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3286 loge("Failed to close pending frozen app sockets: " + e);
3287 }
3288 mPendingFrozenUids.clear();
3289 }
3290
3291 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3292 mNetworkActivityTracker.handleReportNetworkActivity(params);
3293
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003294 final boolean isCellNetworkActivity;
3295 if (mTrackMultiNetworkActivities) {
3296 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3297 // nai could be null if netd receives a netlink message and calls the network
3298 // activity change callback after the network is unregistered from ConnectivityService.
3299 isCellNetworkActivity = nai != null
3300 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3301 } else {
3302 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3303 }
3304
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003305 if (mDelayDestroyFrozenSockets
3306 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003307 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003308 && !mPendingFrozenUids.isEmpty()) {
3309 closePendingFrozenSockets();
3310 }
3311 }
3312
3313 /**
3314 * If the cellular network is no longer the default network, close pending frozen sockets.
3315 *
3316 * @param newNetwork new default network
3317 * @param oldNetwork old default network
3318 */
3319 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3320 NetworkAgentInfo oldNetwork) {
3321 final boolean isOldNetworkCellular = oldNetwork != null
3322 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3323 final boolean isNewNetworkCellular = newNetwork != null
3324 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3325
3326 if (isOldNetworkCellular
3327 && !isNewNetworkCellular
3328 && !mPendingFrozenUids.isEmpty()) {
3329 closePendingFrozenSockets();
3330 }
3331 }
3332
3333 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3334 pw.println("CloseFrozenAppSockets:");
3335 pw.increaseIndent();
3336 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3337 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3338 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3339 pw.decreaseIndent();
3340 }
3341
Junyu Lai155760b2023-10-05 14:51:00 +08003342 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3343 pw.println("Bpf Program Status:");
3344 pw.increaseIndent();
3345 try {
3346 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003347 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003348 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003349 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003350 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003351 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003352 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003353 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003354 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003355 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003356 } catch (IOException e) {
3357 pw.println(" IOException");
3358 }
3359 pw.decreaseIndent();
3360 }
3361
Mark Fasheh7c999d82023-05-04 20:23:11 +00003362 @VisibleForTesting
3363 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003364 @VisibleForTesting
3365 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3366 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003367
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003368 @VisibleForTesting
3369 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3370 "allow_sysui_connectivity_reports";
3371
Yuyang Huang41557552023-11-28 12:47:22 +09003372 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
3373
Paul Jensen83f5d572014-08-29 09:54:01 -04003374 private void enforceInternetPermission() {
3375 mContext.enforceCallingOrSelfPermission(
3376 android.Manifest.permission.INTERNET,
3377 "ConnectivityService");
3378 }
3379
The Android Open Source Project28527d22009-03-03 19:31:44 -08003380 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003381 mContext.enforceCallingOrSelfPermission(
3382 android.Manifest.permission.ACCESS_NETWORK_STATE,
3383 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003384 }
3385
lucaslinc582d502022-01-27 09:07:00 +08003386 private boolean checkAccessPermission(int pid, int uid) {
3387 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3388 == PERMISSION_GRANTED;
3389 }
3390
paulhua6ee2122021-02-22 15:40:43 +08003391 /**
3392 * Performs a strict and comprehensive check of whether a calling package is allowed to
3393 * change the state of network, as the condition differs for pre-M, M+, and
3394 * privileged/preinstalled apps. The caller is expected to have either the
3395 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3396 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3397 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3398 * permission and cannot be revoked. See http://b/23597341
3399 *
3400 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3401 * of this app will be updated to the current time.
3402 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003403 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003404 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3405 == PackageManager.PERMISSION_GRANTED) {
3406 return;
3407 }
3408
3409 if (callingPkg == null) {
3410 throw new SecurityException("Calling package name is null.");
3411 }
3412
3413 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3414 final int uid = mDeps.getCallingUid();
3415 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3416 callingPkg, callingAttributionTag, null /* message */);
3417
3418 if (mode == AppOpsManager.MODE_ALLOWED) {
3419 return;
3420 }
3421
3422 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3423 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3424 return;
3425 }
3426
3427 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3428 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3429 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003430 }
3431
Charles He9369e612017-05-15 17:07:18 +01003432 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003433 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003434 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003435 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003436 }
3437
Quang Luong98858d62023-02-11 00:25:24 +00003438 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003439 enforceAnyPermissionOf(mContext,
3440 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003441 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003442 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3443 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3444 }
3445
paulhu8e96a752019-08-12 16:25:11 +08003446 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003447 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003448 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003449 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003450 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003451 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003452 }
3453
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003454 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003455 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003456 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003457 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003458 android.Manifest.permission.NETWORK_SETTINGS,
3459 android.Manifest.permission.NETWORK_FACTORY,
3460 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3461 }
3462
3463 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003464 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003465 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003466 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003467 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3468 android.Manifest.permission.NETWORK_FACTORY,
3469 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3470 }
3471
lucaslin69e1aa92022-03-22 18:15:09 +08003472 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3473 return PERMISSION_GRANTED == mContext.checkPermission(
3474 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3475 || PERMISSION_GRANTED == mContext.checkPermission(
3476 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3477 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003478 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003479 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003480 }
3481
Chalard Jean9a396cc2018-02-21 18:43:54 +09003482 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003483 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003484 android.Manifest.permission.NETWORK_SETTINGS,
3485 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003486 }
3487
3488 private boolean checkSettingsPermission(int pid, int uid) {
3489 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003490 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3491 || PERMISSION_GRANTED == mContext.checkPermission(
3492 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003493 }
3494
paulhu8e96a752019-08-12 16:25:11 +08003495 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003496 enforceNetworkStackPermissionOr(mContext,
3497 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003498 }
3499
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003500 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003501 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003502 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003503 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003504 }
3505
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003506 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003507 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003508 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3509 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003510 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003511 }
3512
James Mattis8378aec2021-01-26 14:05:36 -08003513 private void enforceOemNetworkPreferencesPermission() {
3514 mContext.enforceCallingOrSelfPermission(
3515 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3516 "ConnectivityService");
3517 }
3518
James Mattisfa270db2021-05-31 17:11:10 -07003519 private void enforceManageTestNetworksPermission() {
3520 mContext.enforceCallingOrSelfPermission(
3521 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3522 "ConnectivityService");
3523 }
3524
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003525 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003526 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003527 android.Manifest.permission.NETWORK_STACK,
3528 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003529 }
3530
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003531 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003532 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003533 android.Manifest.permission.NETWORK_STACK,
3534 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3535 }
3536
Chris Göllnercc962022023-12-26 09:55:32 +00003537 private boolean checkSystemBarServicePermission(int pid, int uid) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003538 return checkAnyPermissionOf(mContext, pid, uid,
3539 android.Manifest.permission.STATUS_BAR_SERVICE);
3540 }
3541
paulhu1a407652019-03-22 16:35:06 +08003542 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003543 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003544 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003545 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3546 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003547 }
3548
Paul Hu8fc2a552022-05-04 18:44:42 +08003549 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3550 boolean checkUidsAllowedList) {
3551 if (PermissionUtils.checkAnyPermissionOf(mContext,
3552 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3553 return true;
3554 }
3555
3556 // fallback to ConnectivityInternalPermission
3557 // TODO: Remove this fallback check after all apps have declared
3558 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3559 if (PermissionUtils.checkAnyPermissionOf(mContext,
3560 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3561 return true;
3562 }
3563
3564 // Check whether uid is in allowed on restricted networks list.
3565 if (checkUidsAllowedList
3566 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3567 return true;
3568 }
3569 return false;
3570 }
3571
3572 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3573 final int callingUid = mDeps.getCallingUid();
3574 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3575 throw new SecurityException("ConnectivityService: user " + callingUid
3576 + " has no permission to access restricted network.");
3577 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003578 }
3579
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003580 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003581 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003582 }
3583
Roshan Pius98f59ec2021-02-23 08:47:39 -08003584 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3585 return PERMISSION_GRANTED == mContext.checkPermission(
3586 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3587 }
3588
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003589 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003590 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003591 }
3592
3593 private void sendInetConditionBroadcast(NetworkInfo info) {
3594 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3595 }
3596
Wink Saville4f0de1e2011-08-04 15:01:58 -07003597 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003598 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003599 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003600 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003601 if (info.isFailover()) {
3602 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3603 info.setFailover(false);
3604 }
3605 if (info.getReason() != null) {
3606 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3607 }
3608 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003609 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3610 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003611 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003612 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003613 return intent;
3614 }
3615
3616 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3617 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3618 }
3619
Michael Groover73f69482023-01-27 11:01:25 -06003620 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3621 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003622 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3623 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003624 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003625 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003626 if (!mSystemReady
3627 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003628 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003629 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003630 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003631 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003632 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003633 }
3634
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003635 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003636 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003637 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003638 final NetworkInfo ni = intent.getParcelableExtra(
3639 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003640 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3641 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003642 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003643 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003644 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003645 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003646 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003647 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003648 } finally {
3649 Binder.restoreCallingIdentity(ident);
3650 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003651 }
3652 }
3653
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003654 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3655 NetworkInfo info) {
3656 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003657 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003658
3659 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3660 try {
3661 // This allows us to discard older broadcasts still waiting to be delivered
3662 // which have the same namespace and key.
3663 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3664 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3665 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003666 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003667 } catch (UnsupportedApiLevelException e) {
3668 Log.wtf(TAG, "Using unsupported API" + e);
3669 }
3670 }
3671
3672 @VisibleForTesting
3673 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3674 final StringBuilder sb = new StringBuilder();
3675 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3676 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3677 sb.append(info.getExtraInfo());
3678 return sb.toString();
3679 }
3680
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003681 /**
Aaron Huang96011892020-06-27 07:18:23 +08003682 * Called by SystemServer through ConnectivityManager when the system is ready.
3683 */
3684 @Override
3685 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003686 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003687 throw new SecurityException("Calling Uid is not system uid.");
3688 }
3689 systemReadyInternal();
3690 }
3691
3692 /**
3693 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003694 */
3695 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003696 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003697 // Load flags after PackageManager is ready to query module version
3698 mFlags.loadFlags(mDeps, mContext);
3699
Aaron Huang9a57acf2020-12-08 10:03:29 +08003700 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3701 // listening network request which is sent by MultipathPolicyTracker won't be added
3702 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3703 // be called after PermissionMonitor#startMonitoring().
3704 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3705 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3706 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003707 final ConditionVariable startMonitoringDone = new ConditionVariable();
3708 mHandler.post(() -> {
3709 mPermissionMonitor.startMonitoring();
3710 startMonitoringDone.open();
3711 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003712 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003713 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003714
Hugo Benichie5220992017-04-26 14:53:28 +09003715 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003716 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003717 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003718 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003719 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003720 }
3721 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003722
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003723 // Create network requests for always-on networks.
3724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003725
3726 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003727 // Note that updating can be skipped here if the list is empty only because no uid
3728 // rules are applied before system ready. Normally, the empty uid list means to clear
3729 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003730 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3731 updateMobileDataPreferredUids();
3732 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003733
3734 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003735 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003736 mBpfNetMaps.setPullAtomCallback(mContext);
3737 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003738 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3739 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003740 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3741 // have permission problem. While CV#block() is unbounded in time and can in principle block
3742 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3743 // could have blocked forever too.
3744 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003745 }
3746
The Android Open Source Project28527d22009-03-03 19:31:44 -08003747 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003748 * Start listening for default data network activity state changes.
3749 */
3750 @Override
3751 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003752 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003753 }
3754
3755 /**
3756 * Stop listening for default data network activity state changes.
3757 */
3758 @Override
3759 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003760 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003761 }
3762
3763 /**
3764 * Check whether the default network radio is currently active.
3765 */
3766 @Override
3767 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003768 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003769 }
3770
3771 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003772 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003773 * and set it on it's iface.
3774 */
Junyu Lai970963e2022-10-25 15:46:47 +08003775 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003776 final String iface = newLp.getInterfaceName();
3777 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003778 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003779 // Silently ignore unset MTU value.
3780 return;
3781 }
Hansen Kurli04252032022-12-07 11:21:49 +00003782 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3783 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3784 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003785 return;
3786 }
Hansen Kurli04252032022-12-07 11:21:49 +00003787 // Cannot set MTU without interface name
3788 if (TextUtils.isEmpty(iface)) {
3789 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003790 return;
3791 }
sy.yun4aa73922013-09-02 05:24:09 +09003792
Hansen Kurli04252032022-12-07 11:21:49 +00003793 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3794 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003795 return;
3796 }
3797
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003798 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003799 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003800 mNetd.interfaceSetMtu(iface, mtu);
3801 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003802 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003803 }
3804 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003805
Chenbo Feng15416292018-11-08 17:36:21 -08003806 @VisibleForTesting
3807 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003808
Junyu Lai970963e2022-10-25 15:46:47 +08003809 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003810 String[] values = null;
3811 if (tcpBufferSizes != null) {
3812 values = tcpBufferSizes.split(",");
3813 }
3814
3815 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003816 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003817 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3818 values = tcpBufferSizes.split(",");
3819 }
3820
3821 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3822
3823 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003824 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003825
Chenbo Feng15416292018-11-08 17:36:21 -08003826 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3827 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3828 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003829 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003830 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003831 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003832 }
3833 }
3834
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003835 @Override
3836 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003837 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003838 NETWORK_RESTORE_DELAY_PROP_NAME);
3839 if(restoreDefaultNetworkDelayStr != null &&
3840 restoreDefaultNetworkDelayStr.length() != 0) {
3841 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003842 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003843 } catch (NumberFormatException e) {
3844 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003845 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003846 // if the system property isn't set, use the value for the apn type
3847 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3848
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003849 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3850 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003851 }
3852 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003853 }
3854
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003855 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003856 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003857 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003858 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003859 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003860 // Start gathering diagnostic information.
3861 netDiags.add(new NetworkDiagnostics(
3862 nai.network,
3863 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003864 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003865 DIAG_TIME_MS));
3866 }
3867
3868 for (NetworkDiagnostics netDiag : netDiags) {
3869 pw.println();
3870 netDiag.waitForMeasurements();
3871 netDiag.dump(pw);
3872 }
3873 }
3874
The Android Open Source Project28527d22009-03-03 19:31:44 -08003875 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003876 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3877 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003878 if (!checkDumpPermission(mContext, TAG, writer)) return;
3879
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003880 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003881 }
3882
lucaslin99473f62020-12-10 15:10:54 +08003883 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3884 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3885 != PackageManager.PERMISSION_GRANTED) {
3886 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003887 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003888 + " due to missing android.permission.DUMP permission");
3889 return false;
3890 } else {
3891 return true;
3892 }
3893 }
3894
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003895 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003896 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003897
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003898 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003899 dumpNetworkDiagnostics(pw);
3900 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003901 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003902 dumpNetworks(pw);
3903 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003904 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003905 dumpNetworkRequests(pw);
3906 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003907 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3908 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3909 dumpTrafficController(pw, fd, verbose);
3910 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003911 }
Erik Kline9647f382015-06-05 17:47:34 +09003912
Junyu Lai0da479b2022-04-20 15:06:29 +08003913 pw.println("NetworkProviders for:");
3914 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003915 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003916 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003917 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003918 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003919 pw.println();
3920
Chalard Jean5b409c72021-02-04 13:12:59 +09003921 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003922 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003923 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003924 pw.println("none");
3925 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003926 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003927 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003928 pw.println();
3929
James Mattis8b298a02021-06-01 22:34:04 -07003930 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003931 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003932 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003933 pw.decreaseIndent();
3934 pw.println();
3935
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003936 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003937 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003938 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003939 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003940 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003941
junyulaif2c67e42018-08-07 19:50:45 +08003942 pw.println("Status for known UIDs:");
3943 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003944 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003945 for (int i = 0; i < size; i++) {
3946 // Don't crash if the array is modified while dumping in bugreports.
3947 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003948 final int uid = mUidBlockedReasons.keyAt(i);
3949 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3950 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003951 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003952 } catch (ArrayIndexOutOfBoundsException e) {
3953 pw.println(" ArrayIndexOutOfBoundsException");
3954 } catch (ConcurrentModificationException e) {
3955 pw.println(" ConcurrentModificationException");
3956 }
3957 }
3958 pw.println();
3959 pw.decreaseIndent();
3960
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003961 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003962 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003963 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003964 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003965 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003966
Junyu Lai0da479b2022-04-20 15:06:29 +08003967 pw.println("Network Offers:");
3968 pw.increaseIndent();
3969 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3970 pw.println(offerInfo.offer);
3971 }
3972 pw.decreaseIndent();
3973 pw.println();
3974
Robert Greenwalt94e22142014-07-30 16:31:24 -07003975 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003976
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003977 pw.println();
markchien5e866652019-09-30 14:40:57 +08003978 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003979
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003980 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003981 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003982
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003983 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003984 dumpCloseFrozenAppSockets(pw);
3985
3986 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003987 dumpBpfProgramStatus(pw);
3988
Chalard Jean53017782022-11-24 17:13:44 +09003989 if (null != mCarrierPrivilegeAuthenticator) {
3990 pw.println();
3991 mCarrierPrivilegeAuthenticator.dump(pw);
3992 }
3993
Junyu Lai155760b2023-10-05 14:51:00 +08003994 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003995
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003996 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003997 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003998 pw.println("mNetworkRequestInfoLogs (most recent first):");
3999 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004000 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09004001 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09004002
4003 pw.println();
4004 pw.println("mNetworkInfoBlockingLogs (most recent first):");
4005 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004006 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09004007 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09004008
4009 pw.println();
4010 pw.println("NetTransition WakeLock activity (most recent first):");
4011 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004012 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
4013 pw.println("total releases: " + mTotalWakelockReleases);
4014 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
4015 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
4016 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4017 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4018 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4019 }
James Mattiscb1e0362021-04-06 17:07:42 -07004020 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004021
4022 pw.println();
4023 pw.println("bandwidth update requests (by uid):");
4024 pw.increaseIndent();
4025 synchronized (mBandwidthRequests) {
4026 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4027 pw.println("[" + mBandwidthRequests.keyAt(i)
4028 + "]: " + mBandwidthRequests.valueAt(i));
4029 }
4030 }
4031 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004032 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004033
James Mattiscb1e0362021-04-06 17:07:42 -07004034 pw.println();
4035 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4036 pw.increaseIndent();
4037 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004038 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004039 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004040
4041 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004042
4043 pw.println();
4044 pw.println("Permission Monitor:");
4045 pw.increaseIndent();
4046 mPermissionMonitor.dump(pw);
4047 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004048
4049 pw.println();
4050 pw.println("Legacy network activity:");
4051 pw.increaseIndent();
4052 mNetworkActivityTracker.dump(pw);
4053 pw.decreaseIndent();
Yang Sunca537d52024-01-19 12:53:50 +08004054
4055 pw.println();
4056 pw.println("Multicast routing supported: " +
4057 (mMulticastRoutingCoordinatorService != null));
The Android Open Source Project28527d22009-03-03 19:31:44 -08004058 }
4059
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004060 private void dumpNetworks(IndentingPrintWriter pw) {
4061 for (NetworkAgentInfo nai : networksSortedById()) {
4062 pw.println(nai.toString());
4063 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004064 pw.println("Nat464Xlat:");
4065 pw.increaseIndent();
4066 nai.dumpNat464Xlat(pw);
4067 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004068 pw.println(String.format(
4069 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4070 nai.numForegroundNetworkRequests(),
4071 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4072 nai.numBackgroundNetworkRequests(),
4073 nai.numNetworkRequests()));
4074 pw.increaseIndent();
4075 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4076 pw.println(nai.requestAt(i).toString());
4077 }
4078 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004079 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004080 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004081 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004082 pw.decreaseIndent();
4083 pw.decreaseIndent();
4084 }
4085 }
4086
James Mattis8b298a02021-06-01 22:34:04 -07004087 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4088 if (!mProfileNetworkPreferences.isEmpty()) {
4089 pw.println("Profile preferences:");
4090 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004091 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004092 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004093 }
James Mattis8b298a02021-06-01 22:34:04 -07004094 if (!mOemNetworkPreferences.isEmpty()) {
4095 pw.println("OEM preferences:");
4096 pw.increaseIndent();
4097 pw.println(mOemNetworkPreferences);
4098 pw.decreaseIndent();
4099 }
4100 if (!mMobileDataPreferredUids.isEmpty()) {
4101 pw.println("Mobile data preferred UIDs:");
4102 pw.increaseIndent();
4103 pw.println(mMobileDataPreferredUids);
4104 pw.decreaseIndent();
4105 }
James Mattis45d81842021-01-10 14:24:24 -08004106
James Mattis8b298a02021-06-01 22:34:04 -07004107 pw.println("Default requests:");
4108 pw.increaseIndent();
4109 dumpPerAppDefaultRequests(pw);
4110 pw.decreaseIndent();
4111 }
4112
4113 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004114 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4115 if (mDefaultRequest == defaultRequest) {
4116 continue;
4117 }
4118
James Mattis8b298a02021-06-01 22:34:04 -07004119 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4120 final String networkOutput;
4121 if (null == satisfier) {
4122 networkOutput = "null";
4123 } else if (mNoServiceNetwork.equals(satisfier)) {
4124 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004125 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004126 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004127 }
James Mattis8b298a02021-06-01 22:34:04 -07004128 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4129 ? "" : " asUid: " + defaultRequest.mAsUid;
4130 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4131 + defaultRequest.mPid + asUidString + "]";
4132 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4133 + " Preference order: " + defaultRequest.mPreferenceOrder
4134 + " Tracked UIDs: " + defaultRequest.getUids();
4135 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004136 }
4137 }
4138
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004139 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004140 NetworkRequestInfo[] infos = null;
4141 while (infos == null) {
4142 try {
4143 infos = requestsSortedById();
4144 } catch (ConcurrentModificationException e) {
4145 // mNetworkRequests should only be accessed from handler thread, except dump().
4146 // As dump() is never called in normal usage, it would be needlessly expensive
4147 // to lock the collection only for its benefit. Instead, retry getting the
4148 // requests if ConcurrentModificationException is thrown during dump().
4149 }
4150 }
4151 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004152 pw.println(nri.toString());
4153 }
4154 }
4155
Ken Chene6d511f2022-01-25 11:10:42 +08004156 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4157 boolean verbose) {
4158 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004159 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004160 } catch (ServiceSpecificException e) {
4161 pw.println(e.getMessage());
4162 } catch (IOException e) {
4163 loge("Dump BPF maps failed, " + e);
4164 }
4165 }
4166
Chalard Jean524f0b12021-10-25 21:11:56 +09004167 private void dumpAllRequestInfoLogsToLogcat() {
4168 try (PrintWriter logPw = new PrintWriter(new Writer() {
4169 @Override
4170 public void write(final char[] cbuf, final int off, final int len) {
4171 // This method is called with 0-length and 1-length arrays for empty strings
4172 // or strings containing only the DEL character.
4173 if (len <= 1) return;
4174 Log.e(TAG, new String(cbuf, off, len));
4175 }
4176 @Override public void flush() {}
4177 @Override public void close() {}
4178 })) {
4179 mNetworkRequestInfoLogs.dump(logPw);
4180 }
4181 }
4182
Hugo Benichia480ba52018-09-03 08:19:02 +09004183 /**
4184 * Return an array of all current NetworkAgentInfos sorted by network id.
4185 */
4186 private NetworkAgentInfo[] networksSortedById() {
4187 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004188 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004189 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004190 return networks;
4191 }
4192
4193 /**
4194 * Return an array of all current NetworkRequest sorted by request id.
4195 */
James Mattis258ea3c2020-11-15 15:04:40 -08004196 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004197 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004198 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004199 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004200 // Sort the array based off the NRI containing the min requestId in its requests.
4201 Arrays.sort(requests,
4202 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4203 Comparator.comparingInt(req -> req.requestId)).requestId
4204 )
4205 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004206 return requests;
4207 }
4208
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004209 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004210 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004211 if (officialNai != null && officialNai.equals(nai)) return true;
4212 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004213 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004214 " - " + nai);
4215 }
4216 return false;
4217 }
4218
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004219 private boolean isDisconnectRequest(Message msg) {
4220 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4221 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4222 return info.getState() == NetworkInfo.State.DISCONNECTED;
4223 }
4224
Robert Greenwalt2034b912009-08-12 16:08:25 -07004225 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004226 private class NetworkStateTrackerHandler extends Handler {
4227 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004228 super(looper);
4229 }
4230
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004231 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004232 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4233 final NetworkAgentInfo nai = arg.first;
4234 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004235 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004236 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004237 }
4238 return;
4239 }
4240
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004241 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004242 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004243 return;
4244 }
4245
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004246 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004247 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004248 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4249 if (!nai.respectsNcStructuralConstraints(proposed)) {
4250 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4251 + nai.networkCapabilities + " -> " + proposed);
4252 disconnectAndDestroyNetwork(nai);
4253 return;
4254 }
4255 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004256 final NetworkCapabilities sanitized =
4257 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004258 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004259 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004260 break;
4261 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004262 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004263 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004264 processLinkPropertiesFromAgent(nai, newLp);
4265 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004266 break;
4267 }
4268 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004269 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004270 updateNetworkInfo(nai, info);
4271 break;
4272 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004273 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4274 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004275 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004276 break;
4277 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004278 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004279 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004280 break;
4281 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004282 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004283 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004284 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004285 // Note that if the NAI had been connected, this would affect the
4286 // score, and therefore would require re-mixing the score and performing
4287 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004288 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004289 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4290 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004291 // Mark the network as temporarily accepting partial connectivity so that it
4292 // will be validated (and possibly become default) even if it only provides
4293 // partial internet access. Note that if user connects to partial connectivity
4294 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4295 // out of wifi coverage) and if the same wifi is available again, the device
4296 // will auto connect to this wifi even though the wifi has "no internet".
4297 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004298 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004299 break;
4300 }
junyulai011b1f12019-01-03 18:50:15 +08004301 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004302 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004303 break;
4304 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004305 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004306 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004307 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004308
4309 if (isLegacyLockdownNai(nai)
4310 && (underlying == null || underlying.size() != 1)) {
4311 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4312 + " must have exactly one underlying network: " + underlying);
4313 }
4314
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004315 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4316 nai.declaredUnderlyingNetworks = (underlying != null)
4317 ? underlying.toArray(new Network[0]) : null;
4318
4319 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4320 if (DBG) {
4321 log(nai.toShortString() + " changed underlying networks to "
4322 + Arrays.toString(nai.declaredUnderlyingNetworks));
4323 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004324 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004325 notifyIfacesChangedForNetworkStats();
4326 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004327 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004328 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004329 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4330 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4331 nai.teardownDelayMs = msg.arg1;
4332 } else {
4333 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4334 }
Chalard Jean550b5212021-03-05 23:07:53 +09004335 break;
4336 }
4337 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4338 nai.setLingerDuration((int) arg.second);
4339 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004340 }
Tyler Wear72388212021-09-09 14:49:02 -07004341 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4342 DscpPolicy policy = (DscpPolicy) arg.second;
4343 if (mDscpPolicyTracker != null) {
4344 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4345 }
4346 break;
4347 }
4348 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4349 if (mDscpPolicyTracker != null) {
4350 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4351 }
4352 break;
4353 }
4354 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4355 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004356 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004357 }
4358 break;
4359 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004360 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004361 if (!nai.everConnected()) {
4362 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4363 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004364 teardownUnneededNetwork(nai);
4365 break;
4366 }
4367
4368 if (nai.isDestroyed()) {
4369 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4370 + ", ignoring");
4371 break;
4372 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004373
4374 final int timeoutMs = (int) arg.second;
4375 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4376 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4377 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4378 }
4379
4380 // Marking a network awaiting replacement is used to ensure that any requests
4381 // satisfied by the network do not switch to another network until a
4382 // replacement is available or the wait for a replacement times out.
4383 // If the network is inactive (i.e., nascent or lingering), then there are no
4384 // such requests, and there is no point keeping it. Just tear it down.
4385 // Note that setLingerDuration(0) cannot be used to do this because the network
4386 // could be nascent.
4387 nai.clearInactivityState();
4388 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4389 Log.d(TAG, nai.toShortString()
4390 + " marked awaiting replacement is unneeded, tearing down instead");
4391 teardownUnneededNetwork(nai);
4392 break;
4393 }
4394
4395 Log.d(TAG, "Marking " + nai.toShortString()
4396 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4397 destroyNativeNetwork(nai);
4398
4399 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4400 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4401 // consider the fact that the network could already have disconnected or been
4402 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4403 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4404 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4405 mKeepaliveTracker.handleStopAllKeepalives(nai,
4406 SocketKeepalive.ERROR_INVALID_NETWORK);
4407
4408 nai.updateScoreForNetworkAgentUpdate();
4409 // This rematch is almost certainly not going to result in any changes, because
4410 // the destroyed flag is only just above the "current satisfier wins"
4411 // tie-breaker. But technically anything that affects scoring should rematch.
4412 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004413 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004414 break;
4415 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004416 }
4417 }
4418
4419 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004420 final int netId = msg.arg2;
4421 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004422 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004423 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004424 switch (msg.what) {
4425 default:
4426 return false;
lucasline117e2e2019-10-22 18:27:33 +08004427 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004428 if (nai == null) {
4429 break;
4430 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004431 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4432 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004433 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004434 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004435 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004436 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004437 if (probePrivateDnsCompleted) {
4438 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4439 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004440 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004441 }
4442 // Only show the notification when the private DNS is broken and the
4443 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004444 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004445 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4446 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004447 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004448 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4449 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4450 // private DNS is broken, it means this network is being reevaluated.
4451 // Either probing private DNS is not necessary any more or it hasn't been
4452 // done yet. In either case, the networkCapabilities should be updated to
4453 // reflect the new status.
4454 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004455 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004456 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004457 }
4458 break;
4459 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004460 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004461 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4462
Erik Kline31b4a9e2018-01-11 21:07:29 +09004463 if (nai == null) break;
4464
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004465 handleNetworkTested(nai, results.mTestResult,
4466 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004467 break;
4468 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004469 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004470 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004471 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004472 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004473 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004474 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004475 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4476 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004477 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004478 if (nai == null) {
4479 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4480 break;
4481 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004482 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004483 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004484 (PendingIntent) msg.obj,
4485 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004486 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004487 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004488 break;
4489 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004490 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004491 if (nai == null) break;
4492
Erik Kline9a62f012018-03-21 07:18:33 -07004493 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004494 break;
4495 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004496 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004497 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004498 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004499 break;
4500 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004501 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004502 return true;
4503 }
4504
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004505 private void handleNetworkTested(
4506 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004507 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4508 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004509 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004510
4511 // If there is any kind of working networking, then the NAI has been evaluated
4512 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4513 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004514 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004515 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004516 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4517 // any callback that receives onAvailable for that rematch receives an extra caps
4518 // callback. To prevent that, update the score in the agent so the updates below won't
4519 // see an update to both caps and score at the same time.
4520 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004521 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4522
he_won.hwang881307a2022-03-15 21:23:52 +09004523 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4524 // Assume the validation failure is due to a temporary failure after roaming
4525 // and ignore it. NetworkMonitor will continue to retry validation. If it
4526 // continues to fail after the block timeout expires, the network will be
4527 // marked unvalidated. If it succeeds, then validation state will not change.
4528 return;
4529 }
4530
Chalard Jean254bd162022-08-25 13:04:51 +09004531 final boolean wasValidated = nai.isValidated();
4532 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004533 final boolean wasPortal = nai.captivePortalDetected();
4534 nai.setPartialConnectivity(partial);
4535 nai.setCaptivePortalDetected(portal);
4536 nai.updateScoreForNetworkAgentUpdate();
4537 final boolean partialConnectivityChanged = (wasPartial != partial);
4538 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004539
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004540 if (DBG) {
4541 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4542 ? " with redirect to " + redirectUrl
4543 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004544 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004545 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004546 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004547 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004548 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004549 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004550 if (valid) {
4551 handleFreshlyValidatedNetwork(nai);
4552 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4553 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004554 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004555 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004556 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004557 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004558 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004559 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004560 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004561 NotificationType.PRIVATE_DNS_BROKEN);
4562 // If network becomes valid, the hasShownBroken should be reset for
4563 // that network so that the notification will be fired when the private
4564 // DNS is broken again.
4565 nai.networkAgentConfig.hasShownBroken = false;
4566 }
4567 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004568 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004569 } else if (portalChanged) {
4570 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004571 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004572 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4573 nai.onPreventAutomaticReconnect();
4574 teardownUnneededNetwork(nai);
4575 return;
4576 } else {
4577 updateCapabilitiesForNetwork(nai);
4578 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004579 } else if (becameEvaluated) {
4580 // If valid or partial connectivity changed, updateCapabilities* has
4581 // done the rematch.
4582 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004583 }
4584 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004585
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004586 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004587 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004588 nai.onValidationStatusChanged(
4589 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4590 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004591
4592 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004593 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004594 // immediately. Re-notify partial connectivity silently if no internet
4595 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004596 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004597 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004598 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4599 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004600 }
4601
Chalard Jean254bd162022-08-25 13:04:51 +09004602 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004603 handleNetworkUnvalidated(nai);
4604 }
4605 }
4606
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004607 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4608 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4609 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4610 // Do not avoid captive portal when network is wear proxy.
4611 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4612 }
4613
Calvin Ondada1452016-10-11 15:10:46 -07004614 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004615 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4616 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004617 }
4618
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004619 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4620 switch (msg.what) {
4621 default:
4622 return false;
4623 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4624 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4625 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4626 handleLingerComplete(nai);
4627 }
4628 break;
4629 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004630 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4631 handleNetworkAgentRegistered(msg);
4632 break;
4633 }
4634 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4635 handleNetworkAgentDisconnected(msg);
4636 break;
4637 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004638 }
4639 return true;
4640 }
4641
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004642 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004643 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004644 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004645 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004646 maybeHandleNetworkAgentMessage(msg);
4647 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004648 }
4649 }
4650
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004651 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004652 private final int mNetId;
4653 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004654
4655 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004656 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004657 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004658 }
4659
4660 @Override
4661 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4662 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004663 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004664 }
4665
4666 @Override
4667 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004668 // Legacy version of notifyNetworkTestedWithExtras.
4669 // Would only be called if the system has a NetworkStack module older than the
4670 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004671 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004672 }
4673
4674 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004675 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004676 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4677 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004678 final Message msg = mTrackerHandler.obtainMessage(
4679 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004680 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004681 new NetworkTestedResults(
4682 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004683 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004684
4685 // Invoke ConnectivityReport generation for this Network test event.
4686 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4687 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004688
Cody Kestingf1120be2020-08-03 18:01:40 -07004689 // NetworkMonitor reports the network validation result as a bitmask while
4690 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4691 // logical value for ConnectivityDiagnostics.
4692 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4693 p.result);
4694
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004695 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004696 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004697 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4698 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4699
Aaron Huang959d3642021-01-21 15:47:41 +08004700 ConnectivityReportEvent reportEvent =
4701 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4702 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004703 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004704 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004705 }
4706
4707 @Override
4708 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4709 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4710 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004711 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004712 }
4713
4714 @Override
lucasline117e2e2019-10-22 18:27:33 +08004715 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4716 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4717 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004718 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004719 }
4720
4721 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004722 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4723 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4724 EVENT_CAPPORT_DATA_CHANGED,
4725 0, mNetId, data));
4726 }
4727
4728 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004729 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004730 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004731 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004732
4733 final PendingIntent pendingIntent;
4734 // Only the system server can register notifications with package "android"
4735 final long token = Binder.clearCallingIdentity();
4736 try {
paulhu7746e4e2020-06-09 19:07:03 +08004737 pendingIntent = PendingIntent.getBroadcast(
4738 mContext,
4739 0 /* requestCode */,
4740 intent,
4741 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004742 } finally {
4743 Binder.restoreCallingIdentity(token);
4744 }
4745 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4746 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004747 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004748 }
4749
4750 @Override
4751 public void hideProvisioningNotification() {
4752 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004753 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004754 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004755
4756 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004757 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004758 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004759 }
4760
4761 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004762 public int getInterfaceVersion() {
4763 return this.VERSION;
4764 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004765
4766 @Override
4767 public String getInterfaceHash() {
4768 return this.HASH;
4769 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004770 }
4771
Cody Kestingf1120be2020-08-03 18:01:40 -07004772 /**
4773 * Converts the given NetworkMonitor-specific validation result bitmask to a
4774 * ConnectivityDiagnostics-specific validation result int.
4775 */
4776 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4777 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4778 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4779 }
4780 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4781 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4782 }
4783 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4784 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4785 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4786 }
4787
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004788 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004789 log("Data stall detected with methods: " + p.detectionMethod);
4790
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004791 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004792 int detectionMethod = 0;
4793 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4794 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4795 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4796 }
4797 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4798 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4799 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4800 p.tcpMetricsCollectionPeriodMillis);
4801 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004802 }
4803
Cody Kestingf53a0752020-04-15 12:33:28 -07004804 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004805 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004806 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004807
4808 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4809 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4810 // the cost of going through two handlers.
4811 mConnectivityDiagnosticsHandler.sendMessage(msg);
4812 }
4813
Cody Kestingb37958e2020-05-15 10:36:01 -07004814 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4815 return (p.detectionMethod & detectionMethod) != 0;
4816 }
4817
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004818 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4819 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004820 }
4821
Erik Klinea73af002018-06-26 18:53:43 +09004822 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4823 if (nai == null) return;
4824 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4825 // in order to restart a validation pass from within netd.
4826 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00004827 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004828 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004829 }
4830 }
4831
Erik Kline31b4a9e2018-01-11 21:07:29 +09004832 private void handlePrivateDnsSettingsChanged() {
4833 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4834
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004835 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004836 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004837 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004838 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4839 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004840 }
4841 }
4842
Erik Kline9a62f012018-03-21 07:18:33 -07004843 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4844 // Private DNS only ever applies to networks that might provide
4845 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004846 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004847
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004848 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004849 // schedule DNS resolutions. If a DNS resolution is required the
4850 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004851 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004852
4853 // With Private DNS bypass support, we can proceed to update the
4854 // Private DNS config immediately, even if we're in strict mode
4855 // and have not yet resolved the provider name into a set of IPs.
4856 updatePrivateDns(nai, cfg);
4857 }
4858
4859 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4860 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004861 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004862 }
4863
dalyk1720e542018-03-05 12:42:22 -05004864 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4865 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4866 if (nai == null) {
4867 return;
4868 }
4869 mDnsManager.updatePrivateDnsValidation(update);
4870 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4871 }
4872
paulhu7c0a2e62021-01-08 00:51:49 +08004873 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004874 int prefixLength) {
4875 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4876 if (nai == null) return;
4877
paulhu7c0a2e62021-01-08 00:51:49 +08004878 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4879 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004880
4881 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004882 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004883 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004884 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004885 prefixLength);
4886 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004887 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004888 return;
4889 }
4890 }
4891
Lorenzo Colittid523d142020-04-01 20:16:30 +09004892 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004893 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4894 }
4895
Hai Shalome58bdc62021-01-11 18:45:34 -08004896 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004897 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004898 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004899 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4900 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4901 }
4902
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004903 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004904 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004905 * @param nai the agent info to update
4906 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004907 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004908 */
junyulai2b6f0c22021-02-03 20:15:30 +08004909 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4910 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4911 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004912 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004913 // one lingered request, set inactive.
4914 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004915 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004916 if (DBG) log("Unsetting inactive " + nai.toShortString());
4917 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004918 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004919 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004920 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004921 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4922 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004923 }
junyulai2b6f0c22021-02-03 20:15:30 +08004924 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004925 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004926 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004927 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004928 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004929 }
4930
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004931 private void handleNetworkAgentRegistered(Message msg) {
4932 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4933 if (!mNetworkAgentInfos.contains(nai)) {
4934 return;
4935 }
4936
4937 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4938 if (VDBG) log("NetworkAgent registered");
4939 } else {
4940 loge("Error connecting NetworkAgent");
4941 mNetworkAgentInfos.remove(nai);
4942 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004943 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004944 synchronized (mNetworkForNetId) {
4945 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004946 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004947 mNetIdManager.releaseNetId(nai.network.getNetId());
4948 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004949 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004950 }
4951 }
4952 }
Paul Jensend5f53392014-11-25 15:26:53 -05004953
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004954 @VisibleForTesting
4955 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004956 // The feature of creating the networks immediately was slated for U, but race conditions
4957 // detected late required this was flagged off.
4958 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4959 // in NetworkAgentTest.
4960 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004961 }
4962
4963 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4964 @NonNull NetworkInfo.State state) {
4965 if (nai.isCreated()) return false;
4966 if (state == NetworkInfo.State.CONNECTED) return true;
4967 if (state != NetworkInfo.State.CONNECTING) {
4968 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004969 if (shouldCreateNetworksImmediately()) {
4970 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4971 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004972 return false;
4973 }
4974 return nai.isVPN() || shouldCreateNetworksImmediately();
4975 }
4976
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004977 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004978 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004979 }
4980
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004981 @VisibleForTesting
4982 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004983 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004984 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004985
4986 // If the network never roamed, return false. The check below is not sufficient if time
4987 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4988 if (nai.lastRoamTime == 0) return false;
4989
he_won.hwang881307a2022-03-15 21:23:52 +09004990 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4991 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004992 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004993 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004994 final long currentTimeMs = SystemClock.elapsedRealtime();
4995 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004996 if (timeSinceLastRoam <= blockTimeOut) {
4997 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4998 return true;
4999 }
5000 }
5001 return false;
5002 }
5003
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005004 private void handleNetworkAgentDisconnected(Message msg) {
5005 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07005006 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005007 }
5008
Chalard Jeand9fffc32018-05-11 20:19:20 +09005009 // Destroys a network, remove references to it from the internal state managed by
5010 // ConnectivityService, free its interfaces and clean up.
5011 // Must be called on the Handler thread.
5012 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005013 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07005014
5015 if (!mNetworkAgentInfos.contains(nai)) return;
5016
Chalard Jeand9fffc32018-05-11 20:19:20 +09005017 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09005018 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005019 }
lucaslinb25c9a62019-02-12 15:30:13 +08005020 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005021 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005022 // A network agent has disconnected.
5023 // TODO - if we move the logic to the network agent (have them disconnect
5024 // because they lost all their requests or because their score isn't good)
5025 // then they would disconnect organically, report their new state and then
5026 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08005027 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005028 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5029 null, null);
5030 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005031 final boolean wasDefault = isDefaultNetwork(nai);
5032 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005033 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005034 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005035 if (mTrackMultiNetworkActivities) {
5036 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5037 // the network becomes no longer the default network.
5038 mNetworkActivityTracker.removeDataActivityTracking(nai);
5039 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005040 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005041 // If this was a local network forwarded to some upstream, or if some local network was
5042 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005043 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005044 // If this is a local network with an upstream selector, remove the associated network
5045 // request.
5046 if (nai.isLocalNetwork()) {
5047 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5048 if (null != selector) {
5049 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5050 }
5051 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005052 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5053 // by other networks that are already connected. Perhaps that can be done by
5054 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5055 // of rematchAllNetworksAndRequests
5056 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005057 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005058
5059 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005060 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5061 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005062 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005063 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005064 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005065 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005066 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005067 synchronized (mNetworkForNetId) {
5068 // Remove the NetworkAgent, but don't mark the netId as
5069 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005070 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005071 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005072 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005073 // Update allowed network lists in netd. This should be called after removing nai
5074 // from mNetworkAgentInfos.
5075 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005076 // Remove all previously satisfied requests.
5077 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005078 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005079 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005080 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005081 if (currentNetwork != null
5082 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005083 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005084 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5085 // rematch not to keep disconnected agents instead of setting it here ; this
5086 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005087 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005088 for (final NetworkOfferInfo noi : mNetworkOffers) {
5089 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005090 }
James Mattise3ef1912020-12-20 11:09:58 -08005091
Chalard Jean5b409c72021-02-04 13:12:59 +09005092 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005093 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005094 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005095 ensureNetworkTransitionWakelock(nai.toShortString());
5096 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005097 }
5098 }
junyulai2b6f0c22021-02-03 20:15:30 +08005099 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005100 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005101 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005102 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005103 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005104 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005105 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005106
Aaron Huang9fe47be2021-06-08 13:11:45 +08005107 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5108 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5109 // not called by the rematch in this case. This is because the code above unset
5110 // this network from the default request's satisfier, and that is what the rematch
5111 // is using as its source data to know what the old satisfier was. So as far as the
5112 // rematch above is concerned, the old default network was null.
5113 // Therefore if there is no new default, the default network was null and is still
5114 // null, thus there was no change so makeDefault() is not called. So if the old
5115 // network had a proxy and there is no new default, the proxy tracker should be told
5116 // that there is no longer a default proxy.
5117 // Strictly speaking this is not essential because having a proxy setting when
5118 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5119 mProxyTracker.setDefaultProxy(null);
5120 }
5121
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005122 // Immediate teardown.
5123 if (nai.teardownDelayMs == 0) {
5124 destroyNetwork(nai);
5125 return;
5126 }
5127
5128 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005129 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305130 try {
5131 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5132 } catch (RemoteException e) {
5133 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5134 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005135 }
5136 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5137 }
5138
5139 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005140 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005141 // Tell netd to clean up the configuration for this network
5142 // (routing rules, DNS, etc).
5143 // This may be slow as it requires a lot of netd shelling out to ip and
5144 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005145 // after we've rematched networks with requests (which might change the default
5146 // network or service a new request from an app), so network traffic isn't interrupted
5147 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005148 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005149 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005150 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005151 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5152 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5153 // false if the network was never created.
5154 // TODO: delete when S is no longer supported.
5155 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005156 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005157 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005158 }
5159
Chalard Jean1e4c2182023-10-06 18:45:53 +09005160 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005161 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005162 // Step 1 : maybe this network was the upstream for one or more local networks.
5163 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5164 if (!local.isLocalNetwork()) continue;
5165 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5166 if (null == selector) continue;
5167 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5168 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5169 // called after removing all associated NRIs from mNetworkRequests.
5170 if (null == nri) continue;
5171 final NetworkAgentInfo satisfier = nri.getSatisfier();
5172 if (disconnecting != satisfier) continue;
5173 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005174 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5175 // correctly contains null as an upstream.
5176 if (sendCallbacks) {
5177 nri.setSatisfier(null, null);
5178 notifyNetworkCallbacks(local,
5179 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5180 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005181 }
5182
5183 // Step 2 : maybe this is a local network that had an upstream.
5184 if (!disconnecting.isLocalNetwork()) return;
5185 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5186 if (null == selector) return;
5187 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5188 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5189 // is called after removing all associated NRIs from mNetworkRequests.
5190 if (null == nri) return;
5191 final NetworkAgentInfo satisfier = nri.getSatisfier();
5192 if (null == satisfier) return;
5193 removeLocalNetworkUpstream(disconnecting, satisfier);
5194 }
5195
5196 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5197 @NonNull final NetworkAgentInfo upstream) {
5198 try {
Yang Sun29037f62023-12-04 10:31:58 +08005199 final String localNetworkInterfaceName = localAgent.linkProperties.getInterfaceName();
5200 final String upstreamNetworkInterfaceName = upstream.linkProperties.getInterfaceName();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005201 mRoutingCoordinatorService.removeInterfaceForward(
Yang Sun29037f62023-12-04 10:31:58 +08005202 localNetworkInterfaceName,
5203 upstreamNetworkInterfaceName);
5204 disableMulticastRouting(localNetworkInterfaceName, upstreamNetworkInterfaceName);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005205 } catch (RemoteException e) {
5206 loge("Couldn't remove interface forward for "
5207 + localAgent.linkProperties.getInterfaceName() + " to "
5208 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5209 }
5210 }
5211
Ken Chen6df7a902021-04-09 15:08:42 +08005212 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005213 try {
5214 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005215 final NativeNetworkConfig config;
5216 if (nai.isVPN()) {
5217 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005218 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005219 return false;
5220 }
5221 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5222 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005223 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005224 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005225 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005226 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005227 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5228 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005229 getNetworkPermission(nai.networkCapabilities),
5230 false /* secure */,
5231 VpnManager.TYPE_VPN_NONE,
5232 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005233 }
Ken Chen6df7a902021-04-09 15:08:42 +08005234 mNetd.networkCreate(config);
5235 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005236 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5237 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005238 return true;
5239 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005240 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005241 return false;
5242 }
5243 }
5244
Ken Chen6df7a902021-04-09 15:08:42 +08005245 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005246 if (mDscpPolicyTracker != null) {
5247 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5248 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005249 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005250 // the interface is going to go away. Don't send the callbacks however ; if the network
5251 // was is being disconnected the callbacks have already been sent, and if it is being
5252 // destroyed pending replacement they will be sent when it is disconnected.
5253 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005254 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005255 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005256 } catch (RemoteException | ServiceSpecificException e) {
5257 loge("Exception destroying network(networkDestroy): " + e);
5258 }
5259 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005260 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005261 } catch (RemoteException | ServiceSpecificException e) {
5262 loge("Exception destroying network: " + e);
5263 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005264 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5265 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5266 // gets created, could add data to DnsManager data structures that will never get deleted.
5267 mDnsManager.removeNetwork(nai.network);
5268
5269 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005270 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005271 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5272 }
5273
Chalard Jean254bd162022-08-25 13:04:51 +09005274 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005275 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005276 }
5277
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005278 // If this method proves to be too slow then we can maintain a separate
5279 // pendingIntent => NetworkRequestInfo map.
5280 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5281 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005282 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5283 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5284 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005285 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005286 return entry.getValue();
5287 }
5288 }
5289 return null;
5290 }
5291
Chalard Jean524f0b12021-10-25 21:11:56 +09005292 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005293 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005294 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5295 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5296 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5297 // bug is fixed.
5298 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005299 throw new IllegalStateException("This NRI is already registered. New : " + nri
5300 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005301 }
5302 }
5303 }
5304 }
5305
Chalard Jeanac9ace02022-01-26 16:54:05 +09005306 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5307 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005308 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005309 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005310 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005311 }
5312 return false;
5313 }
5314
James Mattisf7027322020-12-13 16:28:14 -08005315 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005316 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005317 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5318 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5319 final NetworkRequestInfo existingRequest =
5320 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005321 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005322 if (DBG) {
5323 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5324 + nri.mRequests.get(0) + " because their intents matched.");
5325 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005326 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005327 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005328 }
Erik Kline05f2b402015-04-30 12:58:40 +09005329 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005330 }
5331
James Mattisf7027322020-12-13 16:28:14 -08005332 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005333 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005334 }
5335
James Mattis3ce3d3c2021-02-09 18:18:28 -08005336 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005337 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005338 for (final NetworkRequestInfo nri : nris) {
5339 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005340 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005341 for (final NetworkRequest req : nri.mRequests) {
5342 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005343 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005344 if (req.isListen()) {
5345 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5346 if (req.networkCapabilities.hasSignalStrength()
5347 && network.satisfiesImmutableCapabilitiesOf(req)) {
5348 updateSignalStrengthThresholds(network, "REGISTER", req);
5349 }
James Mattisf7027322020-12-13 16:28:14 -08005350 }
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005351 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5352 mNetworkRequestStateStatsMetrics.onNetworkRequestReceived(req);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005353 }
5354 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005355
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005356 // If this NRI has a satisfier already, it is replacing an older request that
5357 // has been removed. Track it.
5358 final NetworkRequest activeRequest = nri.getActiveRequest();
5359 if (null != activeRequest) {
5360 // If there is an active request, then for sure there is a satisfier.
5361 nri.getSatisfier().addRequest(activeRequest);
5362 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005363 }
James Mattisf7027322020-12-13 16:28:14 -08005364
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005365 if (mFlags.noRematchAllRequestsOnRegister()) {
5366 rematchNetworksAndRequests(nris);
5367 } else {
5368 rematchAllNetworksAndRequests();
5369 }
James Mattis45d81842021-01-10 14:24:24 -08005370
Chalard Jean0354d8c2021-01-12 10:58:56 +09005371 // Requests that have not been matched to a network will not have been sent to the
5372 // providers, because the old satisfier and the new satisfier are the same (null in this
5373 // case). Send these requests to the providers.
5374 for (final NetworkRequestInfo nri : nris) {
5375 for (final NetworkOfferInfo noi : mNetworkOffers) {
5376 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005377 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005378 }
5379 }
5380
James Mattisf7027322020-12-13 16:28:14 -08005381 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5382 final int callingUid) {
5383 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005384 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005385 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5386 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5387 handleReleaseNetworkRequest(
5388 nri.mRequests.get(0),
5389 callingUid,
5390 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005391 }
5392 }
5393
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005394 // Determines whether the network is the best (or could become the best, if it validated), for
5395 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5396 // on the value of reason:
5397 //
5398 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5399 // then it should be torn down.
5400 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5401 // then it should be lingered.
5402 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005403 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005404
Chalard Jean254bd162022-08-25 13:04:51 +09005405 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005406 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5407 return false;
5408 }
5409
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005410 final int numRequests;
5411 switch (reason) {
5412 case TEARDOWN:
5413 numRequests = nai.numRequestNetworkRequests();
5414 break;
5415 case LINGER:
5416 numRequests = nai.numForegroundNetworkRequests();
5417 break;
5418 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005419 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005420 return true;
5421 }
5422
Chalard Jean947acd42021-03-08 22:29:27 +09005423 if (numRequests > 0) return false;
5424
Paul Jensende49eb12015-06-25 15:30:08 -04005425 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005426 if (reason == UnneededFor.LINGER
5427 && !nri.isMultilayerRequest()
5428 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005429 // Background requests don't affect lingering.
5430 continue;
5431 }
5432
James Mattis3d229892020-11-16 16:46:28 -08005433 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005434 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005435 }
5436 }
Paul Jensende49eb12015-06-25 15:30:08 -04005437 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005438 }
5439
James Mattis3d229892020-11-16 16:46:28 -08005440 private boolean isNetworkPotentialSatisfier(
5441 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005442 // While destroyed network sometimes satisfy requests (including occasionally newly
5443 // satisfying requests), *potential* satisfiers are networks that might beat a current
5444 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5445 // because it's never a good idea to keep a destroyed network in case it validates.
5446 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5447 // candidate after it's been replaced by another unvalidated network.
5448 if (candidate.isDestroyed()) return false;
5449 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005450 // request, return immediately. For multilayer requests, check to see if any of the
5451 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005452 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5453 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005454 return false;
5455 }
5456 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005457 // This multilayer listen request is satisfied therefore no further requests need to be
5458 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005459 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005460 return false;
5461 }
James Mattis3d229892020-11-16 16:46:28 -08005462 // As non-multilayer listen requests have already returned, the below would only happen
5463 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005464 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005465 continue;
5466 }
Chalard Jean80685f42023-10-30 18:31:27 +09005467 // If there is hope for this network might validate and subsequently become the best
5468 // network for that request, then it is needed. Note that this network can't already
5469 // be the best for this request, or it would be the current satisfier, and therefore
5470 // there would be no need to call this method to find out if it is a *potential*
5471 // satisfier ("unneeded", the only caller, only calls this if this network currently
5472 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005473 if (candidate.satisfies(req)) {
5474 // As soon as a network is found that satisfies a request, return. Specifically for
5475 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5476 // is important so as to not evaluate lower priority requests further in
5477 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005478 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5479 ? nri.getSatisfier() : null;
5480 // Note that this catches two important cases:
5481 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5482 // is currently satisfying the request. This is desirable when
5483 // cellular ends up validating but WiFi does not.
5484 // 2. Unvalidated WiFi will not be reaped when validated cellular
5485 // is currently satisfying the request. This is desirable when
5486 // WiFi ends up validating and out scoring cellular.
5487 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005488 }
5489 }
5490
5491 return false;
5492 }
5493
Erik Kline0c04b742016-07-07 16:50:58 +09005494 private NetworkRequestInfo getNriForAppRequest(
5495 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005496 // Looking up the app passed param request in mRequests isn't possible since it may return
5497 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5498 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005499 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5500 // to avoid potential race conditions when validating a package->uid mapping when sending
5501 // the callback on the very low-chance that an application shuts down prior to the callback
5502 // being sent.
5503 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5504 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005505
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005506 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005507 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005508 log(String.format("UID %d attempted to %s for unowned request %s",
5509 callingUid, requestedOperation, nri));
5510 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005511 }
Erik Kline0c04b742016-07-07 16:50:58 +09005512 }
5513
5514 return nri;
5515 }
5516
James Mattisf7027322020-12-13 16:28:14 -08005517 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5518 final String callingMethod) {
5519 if (nri.isMultilayerRequest()) {
5520 throw new IllegalStateException(
5521 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005522 }
5523 }
5524
James Mattisf7027322020-12-13 16:28:14 -08005525 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005526 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005527 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5528 // single NetworkRequest and thus does not apply to multilayer requests.
5529 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5530 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005531 return;
5532 }
James Mattis2516da32021-01-31 17:06:19 -08005533 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005534 return;
5535 }
James Mattisf7027322020-12-13 16:28:14 -08005536 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5537 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005538 }
5539 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005540 callCallbackForRequest(
5541 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005542 }
5543
James Mattisf7027322020-12-13 16:28:14 -08005544 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5545 final int callingUid,
5546 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005547 final NetworkRequestInfo nri =
5548 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5549 if (nri == null) {
5550 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005551 }
James Mattisf7027322020-12-13 16:28:14 -08005552 if (VDBG || (DBG && request.isRequest())) {
5553 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005554 }
5555 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005556 if (callOnUnavailable) {
5557 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5558 }
Erik Kline155a59a2015-11-25 12:49:38 +09005559 }
Erik Kline0c04b742016-07-07 16:50:58 +09005560
James Mattisa076c532020-12-02 14:12:41 -08005561 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005562 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005563 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005564 if (null == mNetworkRequests.remove(req)) {
5565 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5566 continue;
5567 }
James Mattisa076c532020-12-02 14:12:41 -08005568 if (req.isListen()) {
5569 removeListenRequestFromNetworks(req);
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005570 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5571 mNetworkRequestStateStatsMetrics.onNetworkRequestRemoved(req);
James Mattisa076c532020-12-02 14:12:41 -08005572 }
5573 }
James Mattis8f036802021-06-20 16:26:01 -07005574 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005575 if (mDefaultNetworkRequests.remove(nri)) {
5576 // If this request was one of the defaults, then the UID rules need to be updated
5577 // WARNING : if the app(s) for which this network request is the default are doing
5578 // traffic, this will kill their connected sockets, even if an equivalent request
5579 // is going to be reinstated right away ; unconnected traffic will go on the default
5580 // until the new default is set, which will happen very soon.
5581 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5582 // remove ranges for those requests that won't have a replacement
5583 final NetworkAgentInfo satisfier = nri.getSatisfier();
5584 if (null != satisfier) {
5585 try {
paulhu0e79d952021-06-09 16:11:35 +08005586 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5587 satisfier.network.getNetId(),
5588 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005589 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005590 } catch (RemoteException e) {
5591 loge("Exception setting network preference default network", e);
5592 }
5593 }
5594 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005595
Junyu Lai00d92df2022-07-05 11:01:52 +08005596 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005597 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005598 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005599
5600 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005601 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005602 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005603 }
5604 }
5605
Chalard Jean0354d8c2021-01-12 10:58:56 +09005606 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5607 // needed for this offer.
5608 for (final NetworkOfferInfo noi : mNetworkOffers) {
5609 for (final NetworkRequest req : nri.mRequests) {
5610 if (req.isRequest() && noi.offer.neededFor(req)) {
5611 noi.offer.onNetworkUnneeded(req);
5612 }
5613 }
5614 }
James Mattisa076c532020-12-02 14:12:41 -08005615 }
5616
James Mattis3ce3d3c2021-02-09 18:18:28 -08005617 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5618 for (final NetworkRequestInfo nri : nris) {
5619 if (mDefaultRequest == nri) {
5620 // Make sure we never remove the default request.
5621 continue;
5622 }
5623 handleRemoveNetworkRequest(nri);
5624 }
5625 }
5626
James Mattisa076c532020-12-02 14:12:41 -08005627 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5628 // listens don't have a singular affected Network. Check all networks to see
5629 // if this listen request applies and remove it.
5630 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5631 nai.removeRequest(req.requestId);
5632 if (req.networkCapabilities.hasSignalStrength()
5633 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5634 updateSignalStrengthThresholds(nai, "RELEASE", req);
5635 }
5636 }
5637 }
5638
5639 /**
5640 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5641 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5642 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5643 */
5644 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5645 boolean wasKept = false;
5646 final NetworkAgentInfo nai = nri.getSatisfier();
5647 if (nai != null) {
5648 final int requestLegacyType = nri.getActiveRequest().legacyType;
5649 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5650 nai.removeRequest(nri.getActiveRequest().requestId);
5651 if (VDBG || DDBG) {
5652 log(" Removing from current network " + nai.toShortString()
5653 + ", leaving " + nai.numNetworkRequests() + " requests.");
5654 }
5655 // If there are still lingered requests on this network, don't tear it down,
5656 // but resume lingering instead.
5657 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005658 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005659 notifyNetworkLosing(nai, now);
5660 }
5661 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5662 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5663 teardownUnneededNetwork(nai);
5664 } else {
5665 wasKept = true;
5666 }
James Mattisa076c532020-12-02 14:12:41 -08005667 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5668 // Went from foreground to background.
5669 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005670 }
5671
Erik Kline0c04b742016-07-07 16:50:58 +09005672 // Maintain the illusion. When this request arrived, we might have pretended
5673 // that a network connected to serve it, even though the network was already
5674 // connected. Now that this request has gone away, we might have to pretend
5675 // that the network disconnected. LegacyTypeTracker will generate that
5676 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005677 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005678 boolean doRemove = true;
5679 if (wasKept) {
5680 // check if any of the remaining requests for this network are for the
5681 // same legacy type - if so, don't remove the nai
5682 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5683 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005684 if (otherRequest.legacyType == requestLegacyType
5685 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005686 if (DBG) log(" still have other legacy request - leaving");
5687 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005688 }
5689 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005690 }
5691
Erik Kline0c04b742016-07-07 16:50:58 +09005692 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005693 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005694 }
5695 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005696 }
5697 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005698
Junyu Lai00d92df2022-07-05 11:01:52 +08005699 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005700 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005701 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5702 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5703 }
5704
Lorenzo Colittid6459092016-07-04 12:55:44 +09005705 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005706 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005707 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005708 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005709 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005710 }
5711
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005712 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005713 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5714 enforceNetworkStackSettingsOrSetup();
5715 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5716 encodeBool(accept), encodeBool(always), network));
5717 }
5718
5719 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005720 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005721 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005722 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5723 }
5724
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005725 @Override
5726 public void setTestAllowBadWifiUntil(long timeMs) {
5727 enforceSettingsPermission();
5728 if (!Build.isDebuggable()) {
5729 throw new IllegalStateException("Does not support in non-debuggable build");
5730 }
5731
5732 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5733 throw new IllegalArgumentException("It should not exceed "
5734 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5735 }
5736
5737 mHandler.sendMessage(
5738 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5739 }
5740
chiachangwange0192a72023-02-06 13:25:01 +00005741 @Override
5742 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5743 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005744
5745 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5746 throw new IllegalArgumentException("Argument should not exceed "
5747 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5748 }
5749
5750 mHandler.sendMessage(
5751 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5752 }
5753
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005754 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5755 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5756 " accept=" + accept + " always=" + always);
5757
5758 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5759 if (nai == null) {
5760 // Nothing to do.
5761 return;
5762 }
5763
Chalard Jean254bd162022-08-25 13:04:51 +09005764 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005765 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005766 return;
5767 }
5768
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005769 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005770 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005771 }
5772
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005773 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5774 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005775 // If network becomes partial connectivity and user already accepted to use this
5776 // network, we should respect the user's option and don't need to popup the
5777 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005778 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005779 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005780 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005781 }
5782
5783 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005784 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005785 }
5786
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005787 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005788 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005789 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005790 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005791 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005792 }
5793
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005794 }
5795
lucaslin2240ef62019-03-12 13:08:03 +08005796 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5797 boolean always) {
5798 if (DBG) {
5799 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5800 + " always=" + always);
5801 }
5802
5803 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5804 if (nai == null) {
5805 // Nothing to do.
5806 return;
5807 }
5808
Chalard Jean254bd162022-08-25 13:04:51 +09005809 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005810 // The network validated while the dialog box was up. Take no action.
5811 return;
5812 }
5813
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005814 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5815 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005816 }
5817
5818 // TODO: Use the current design or save the user choice into IpMemoryStore.
5819 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005820 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005821 }
5822
5823 if (!accept) {
5824 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005825 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005826 // Tear down the network.
5827 teardownUnneededNetwork(nai);
5828 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005829 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5830 // result in a partial connectivity result which will be processed by
5831 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005832 //
5833 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5834 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005835 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005836 }
5837 }
5838
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005839 private void handleSetAvoidUnvalidated(Network network) {
5840 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005841 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005842 // Nothing to do. The network either disconnected or revalidated.
5843 return;
5844 }
Chalard Jean254bd162022-08-25 13:04:51 +09005845 if (0L == nai.getAvoidUnvalidated()) {
5846 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005847 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005848 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005849 }
5850 }
5851
Chalard Jean5fb43c72022-09-08 19:03:14 +09005852 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005853 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005854 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005855 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005856 }
5857
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005858 @Override
5859 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005860 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005861 mHandler.post(() -> {
5862 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5863 if (nai == null) return;
5864 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005865 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005866 });
5867 }
5868
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005869 /**
5870 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5871 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005872 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005873 * @param appExtras Bundle to use as intent extras for the captive portal application.
5874 * Must be treated as opaque to avoid preventing the captive portal app to
5875 * update its arguments.
5876 */
5877 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005878 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005879 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5880 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005881
5882 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5883 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005884 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5885 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005886 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5887
lucaslin75ff7022020-12-17 04:14:35 +08005888 final long token = Binder.clearCallingIdentity();
5889 try {
5890 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5891 } finally {
5892 Binder.restoreCallingIdentity(token);
5893 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005894 }
5895
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005896 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5897 private final Network mNetwork;
5898
5899 private CaptivePortalImpl(Network network) {
5900 mNetwork = network;
5901 }
5902
5903 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005904 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005905 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5906 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005907 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5908 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5909 // Since the network will be disconnected, skip notifying NetworkMonitor
5910 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005911 }
5912
Chiachang Wang938bfba2020-01-09 13:50:55 +08005913 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005914 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005915 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005916 }
5917
5918 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005919 public void appRequest(final int request) {
5920 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5921 if (nm == null) return;
5922
5923 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005924 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005925 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005926 }
5927 }
5928
5929 @Nullable
5930 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5931 // getNetworkAgentInfoForNetwork is thread-safe
5932 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5933 if (nai == null) return null;
5934
5935 // nai.networkMonitor() is thread-safe
5936 return nai.networkMonitor();
5937 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005938 }
5939
Hugo Benichic9048bc2016-09-14 23:23:08 +00005940 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005941 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005942 }
5943
Chalard Jean020b93a2022-09-01 13:20:14 +09005944 private boolean activelyPreferBadWifi() {
5945 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5946 }
5947
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005948 /**
5949 * Return whether the device should maintain continuous, working connectivity by switching away
5950 * from WiFi networks having no connectivity.
5951 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5952 */
5953 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005954 if (!checkNetworkStackPermission()) {
5955 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5956 }
5957 return avoidBadWifi();
5958 }
5959
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005960 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005961 ensureRunningOnConnectivityServiceThread();
5962 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005963 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005964 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005965 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005966 if (avoidBadWifi) {
5967 // If the device is now avoiding bad wifi, remove notifications that might have
5968 // been put up when the device didn't.
5969 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5970 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005971 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005972 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5973 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5974 for (final NetworkOfferInfo noi : offersToUpdate) {
5975 updateOfferScore(noi.offer);
5976 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005977 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005978 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005979 }
5980
Erik Kline95ecfee2016-10-02 18:02:14 +09005981 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005982 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005983 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005984 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005985 if (!configRestrict) {
5986 pw.println("Bad Wi-Fi avoidance: unrestricted");
5987 return;
5988 }
5989
5990 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5991 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005992 pw.println("Config restrict: " + configRestrict);
5993 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005994
Chalard Jeane0fdea32022-09-14 21:44:22 +09005995 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005996 String description;
5997 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005998 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005999 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006000 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006001 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006002 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006003 description = "avoid";
6004 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09006005 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006006 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09006007 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00006008
6009 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
6010 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09006011 if (null == configValue) {
6012 description = "unset";
6013 } else if (configValue) {
6014 description = "force true";
6015 } else {
6016 description = "force false";
6017 }
6018 pw.println("Actively prefer bad wifi conf: " + description);
6019 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006020 pw.println("Network overrides:");
6021 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09006022 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09006023 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09006024 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006025 }
6026 }
6027 pw.decreaseIndent();
6028 pw.decreaseIndent();
6029 }
6030
paulhu7746e4e2020-06-09 19:07:03 +08006031 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
6032 // unify the method.
6033 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
6034 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
6035 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
6036 return settingsComponent != null
6037 ? settingsComponent.getPackageName() : "com.android.settings";
6038 }
6039
lucaslinb1e8e382019-01-24 15:55:30 +08006040 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006041 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006042 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006043 switch (type) {
6044 case NO_INTERNET:
6045 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006046 // High priority because it is only displayed for explicitly selected networks.
6047 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006048 break;
lucasline117e2e2019-10-22 18:27:33 +08006049 case PRIVATE_DNS_BROKEN:
6050 action = Settings.ACTION_WIRELESS_SETTINGS;
6051 // High priority because we should let user know why there is no internet.
6052 highPriority = true;
6053 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006054 case LOST_INTERNET:
6055 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006056 // High priority because it could help the user avoid unexpected data usage.
6057 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006058 break;
lucaslin2240ef62019-03-12 13:08:03 +08006059 case PARTIAL_CONNECTIVITY:
6060 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006061 // Don't bother the user with a high-priority notification if the network was not
6062 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006063 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006064 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006065 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006066 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006067 return;
6068 }
6069
6070 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006071 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006072 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006073 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006074 // Some OEMs have their own Settings package. Thus, need to get the current using
6075 // Settings package name instead of just use default name "com.android.settings".
6076 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6077 intent.setClassName(settingsPkgName,
6078 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006079 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006080
paulhu2af50222020-10-11 22:52:27 +08006081 PendingIntent pendingIntent = PendingIntent.getActivity(
6082 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006083 0 /* requestCode */,
6084 intent,
paulhu2af50222020-10-11 22:52:27 +08006085 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006086
Serik Beketayevec8ad212020-12-07 22:43:07 -08006087 mNotifier.showNotification(
6088 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006089 }
6090
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006091 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6092 // Don't prompt if the network is validated, and don't prompt on captive portals
6093 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006094 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006095 return false;
6096 }
6097
6098 // If a network has partial connectivity, always prompt unless the user has already accepted
6099 // partial connectivity and selected don't ask again. This ensures that if the device
6100 // automatically connects to a network that has partial Internet access, the user will
6101 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006102 // because we have prompted them.
6103 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006104 return true;
6105 }
6106
6107 // If a network has no Internet access, only prompt if the network was explicitly selected
6108 // and if the user has not already told us to use the network regardless of whether it
6109 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006110 if (nai.networkAgentConfig.explicitlySelected
6111 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006112 return true;
6113 }
6114
6115 return false;
6116 }
6117
Chalard Jean5fb43c72022-09-08 19:03:14 +09006118 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6119 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006120
Chalard Jean5fb43c72022-09-08 19:03:14 +09006121 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6122 if (null == nai) return;
6123
6124 if (nai.setEvaluated()) {
6125 // If setEvaluated() returned true, the network never had any form of connectivity.
6126 // This may have an impact on request matching if bad WiFi avoidance is off and the
6127 // network was found not to have Internet access.
6128 nai.updateScoreForNetworkAgentUpdate();
6129 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006130
6131 // Also, if this is WiFi and it should be preferred actively, now is the time to
6132 // prompt the user that they walked past and connected to a bad WiFi.
6133 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6134 && !avoidBadWifi()
6135 && activelyPreferBadWifi()) {
6136 // The notification will be removed if the network validates or disconnects.
6137 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6138 return;
6139 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006140 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006141
Chalard Jean5fb43c72022-09-08 19:03:14 +09006142 if (!shouldPromptUnvalidated(nai)) return;
6143
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006144 // Stop automatically reconnecting to this network in the future. Automatically connecting
6145 // to a network that provides no or limited connectivity is not useful, because the user
6146 // cannot use that network except through the notification shown by this method, and the
6147 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006148 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006149
Chalard Jean254bd162022-08-25 13:04:51 +09006150 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006151 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006152 } else {
6153 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6154 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006155 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006156
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006157 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6158 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006159 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006160
lucaslin2240ef62019-03-12 13:08:03 +08006161 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6162 return;
6163 }
6164
6165 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006166 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006167 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006168 }
6169
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006170 @Override
6171 public int getMultipathPreference(Network network) {
6172 enforceAccessPermission();
6173
6174 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006175 if (nai != null && nai.networkCapabilities
6176 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006177 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6178 }
6179
Aaron Huang9a57acf2020-12-08 10:03:29 +08006180 final NetworkPolicyManager netPolicyManager =
6181 mContext.getSystemService(NetworkPolicyManager.class);
6182
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006183 final long token = Binder.clearCallingIdentity();
6184 final int networkPreference;
6185 try {
6186 networkPreference = netPolicyManager.getMultipathPreference(network);
6187 } finally {
6188 Binder.restoreCallingIdentity(token);
6189 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006190 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006191 return networkPreference;
6192 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006193 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6194 }
6195
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006196 @Override
6197 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006198 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006199 }
6200
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006201 private class InternalHandler extends Handler {
6202 public InternalHandler(Looper looper) {
6203 super(looper);
6204 }
6205
6206 @Override
6207 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006208 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006209 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006210 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006211 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006212 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006213 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006214 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006215 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006216 break;
6217 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006218 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006219 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006220 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006221 break;
6222 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006223 case EVENT_REGISTER_NETWORK_PROVIDER: {
6224 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006225 break;
6226 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006227 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6228 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006229 break;
6230 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006231 case EVENT_REGISTER_NETWORK_OFFER: {
6232 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6233 break;
6234 }
6235 case EVENT_UNREGISTER_NETWORK_OFFER: {
6236 final NetworkOfferInfo offer =
6237 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6238 if (null != offer) {
6239 handleUnregisterNetworkOffer(offer);
6240 }
6241 break;
6242 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006243 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006244 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6245 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6246 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006247 break;
6248 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006249 case EVENT_REGISTER_NETWORK_REQUEST:
6250 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006251 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006252 break;
6253 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006254 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6255 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006256 handleRegisterNetworkRequestWithIntent(msg);
6257 break;
6258 }
Erik Kline155a59a2015-11-25 12:49:38 +09006259 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6260 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6261 handleTimedOutNetworkRequest(nri);
6262 break;
6263 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006264 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6265 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6266 break;
6267 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006268 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006269 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6270 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006271 break;
6272 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006273 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006274 Network network = (Network) msg.obj;
6275 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006276 break;
6277 }
lucaslin2240ef62019-03-12 13:08:03 +08006278 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6279 Network network = (Network) msg.obj;
6280 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6281 toBool(msg.arg2));
6282 break;
6283 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006284 case EVENT_SET_AVOID_UNVALIDATED: {
6285 handleSetAvoidUnvalidated((Network) msg.obj);
6286 break;
6287 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006288 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6289 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006290 break;
6291 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006292 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6293 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006294 break;
6295 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006296 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6297 // handler thread.
6298 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006299 mKeepaliveTracker.handleStartKeepalive(msg);
6300 break;
6301 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006302 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006303 final AutomaticOnOffKeepalive ki =
6304 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6305 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006306
chiachangwang676c84e2023-02-14 09:22:05 +00006307 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006308 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006309 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006310 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006311 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6312 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006313 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6314 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006315 }
6316 }
6317
6318 // If the network no longer exists, then the keepalive should have been
6319 // cleaned up already. There is no point trying to resume keepalives.
6320 if (!networkFound) return;
6321
chiachangwang676c84e2023-02-14 09:22:05 +00006322 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006323 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wangac2e8f32024-01-18 12:55:11 +00006324 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006325 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006326 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006327 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006328 }
6329 break;
6330 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006331 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006332 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006333 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6334 (IBinder) msg.obj);
6335 if (ki == null) {
6336 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006337 return;
6338 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006339 final int reason = msg.arg2;
6340 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006341 break;
6342 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006343 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6344 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6345 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006346 break;
6347 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006348 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6349 handlePrivateDnsSettingsChanged();
6350 break;
dalyk1720e542018-03-05 12:42:22 -05006351 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6352 handlePrivateDnsValidationUpdate(
6353 (PrivateDnsValidationUpdate) msg.obj);
6354 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006355 case EVENT_UID_BLOCKED_REASON_CHANGED:
6356 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006357 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006358 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6359 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6360 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006361 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006362 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6363 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006364 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006365 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006366 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006367 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006368 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6369 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006370 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006371 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006372 }
lucaslin1193a5d2021-01-21 02:04:15 +08006373 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006374 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006375 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006376 break;
paulhu51f77dc2021-06-07 02:34:20 +00006377 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6378 handleMobileDataPreferredUidsChanged();
6379 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006380 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6381 final long timeMs = ((Long) msg.obj).longValue();
6382 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6383 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006384 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6385 handleIngressRateLimitChanged();
6386 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006387 case EVENT_USER_DOES_NOT_WANT:
6388 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6389 if (nai == null) break;
6390 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006391 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006392 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006393 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6394 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6395 break;
chiachangwange0192a72023-02-06 13:25:01 +00006396 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6397 final long time = ((Long) msg.obj).longValue();
6398 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6399 break;
6400 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006401 case EVENT_UID_FROZEN_STATE_CHANGED:
6402 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6403 handleFrozenUids(args.mUids, args.mFrozenStates);
6404 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006405 }
6406 }
6407 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006408
Lorenzo Colittid6459092016-07-04 12:55:44 +09006409 @Override
markchien5776f962019-12-16 20:15:20 +08006410 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006411 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006412 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006413 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6414 Context.TETHERING_SERVICE);
6415 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006416 }
6417
Lorenzo Colittid6459092016-07-04 12:55:44 +09006418 @Override
markchien5776f962019-12-16 20:15:20 +08006419 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006420 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006421 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006422 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6423 Context.TETHERING_SERVICE);
6424 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006425 }
6426
Lorenzo Colittid6459092016-07-04 12:55:44 +09006427 @Override
markchien5776f962019-12-16 20:15:20 +08006428 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006429 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006430 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006431 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6432 Context.TETHERING_SERVICE);
6433 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006434 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006435
markchien5776f962019-12-16 20:15:20 +08006436
Lorenzo Colittid6459092016-07-04 12:55:44 +09006437 @Override
markchien5776f962019-12-16 20:15:20 +08006438 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006439 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006440 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006441 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6442 Context.TETHERING_SERVICE);
6443
6444 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006445 }
6446
Lorenzo Colittid6459092016-07-04 12:55:44 +09006447 @Override
markchien5776f962019-12-16 20:15:20 +08006448 @Deprecated
6449 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006450 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006451 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6452 Context.TETHERING_SERVICE);
6453
6454 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006455 }
6456
Udam Saini8f7d6a72017-06-07 12:06:28 -07006457 @Override
markchien5776f962019-12-16 20:15:20 +08006458 @Deprecated
6459 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006460 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006461 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6462 Context.TETHERING_SERVICE);
6463 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006464 }
6465
Robert Greenwalte0b00512014-07-02 09:59:16 -07006466 // Called when we lose the default network and have no replacement yet.
6467 // This will automatically be cleared after X seconds or a new default network
6468 // becomes CONNECTED, whichever happens first. The timer is started by the
6469 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006470 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006471 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006472 if (mNetTransitionWakeLock.isHeld()) {
6473 return;
6474 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006475 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006476 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6477 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006478 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006479 mWakelockLogs.log("ACQUIRE for " + forWhom);
6480 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006481 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006482 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006483 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006484 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006485
Hugo Benichi471b62a2017-03-30 23:18:10 +09006486 // Called when we gain a new default network to release the network transition wakelock in a
6487 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6488 // message is cancelled.
6489 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006490 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006491 if (!mNetTransitionWakeLock.isHeld()) {
6492 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006493 }
6494 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006495 // Cancel self timeout on wakelock hold.
6496 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6497 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6498 mHandler.sendMessageDelayed(msg, 1000);
6499 }
6500
6501 // Called when either message of ensureNetworkTransitionWakelock or
6502 // scheduleReleaseNetworkTransitionWakelock is processed.
6503 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6504 String event = eventName(eventId);
6505 synchronized (this) {
6506 if (!mNetTransitionWakeLock.isHeld()) {
6507 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006508 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006509 return;
6510 }
6511 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006512 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6513 mTotalWakelockDurationMs += lockDuration;
6514 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6515 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006516 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006517 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006518 }
6519
Robert Greenwalt986c7412010-09-08 15:24:47 -07006520 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006521 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006522 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006523 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006524 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006525 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006526 }
6527
Lorenzo Colittid6459092016-07-04 12:55:44 +09006528 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006529 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006530 enforceAccessPermission();
6531 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006532 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006533 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006534
6535 final NetworkAgentInfo nai;
6536 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006537 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006538 } else {
6539 nai = getNetworkAgentInfoForNetwork(network);
6540 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006541
6542 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006543 mHandler.obtainMessage(
6544 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006545 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006546
Hugo Benichid6b510a2017-04-06 17:22:18 +09006547 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006548 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006549 if (nai == null
6550 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006551 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006552 return;
6553 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006554 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006555 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006556 mConnectivityDiagnosticsHandler.sendMessage(
6557 mConnectivityDiagnosticsHandler.obtainMessage(
6558 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6559 new ReportedNetworkConnectivityInfo(
6560 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006561 return;
6562 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006563 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006564 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006565 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006566 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006567 // Validating a network that has not yet connected could result in a call to
6568 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006569 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006570 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006571 }
paulhu7aeba372020-12-30 00:42:19 +08006572 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6573 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006574 return;
6575 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006576
6577 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6578 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6579 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6580 // completed.
6581 mConnectivityDiagnosticsHandler.sendMessage(
6582 mConnectivityDiagnosticsHandler.obtainMessage(
6583 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6584 new ReportedNetworkConnectivityInfo(
6585 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006586 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006587 }
6588
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006589 // TODO: call into netd.
6590 private boolean queryUserAccess(int uid, Network network) {
6591 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6592 if (nai == null) return false;
6593
6594 // Any UID can use its default network.
6595 if (nai == getDefaultNetworkForUid(uid)) return true;
6596
6597 // Privileged apps can use any network.
6598 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6599 return true;
6600 }
6601
6602 // An unprivileged UID can use a VPN iff the VPN applies to it.
6603 if (nai.isVPN()) {
6604 return nai.networkCapabilities.appliesToUid(uid);
6605 }
6606
6607 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6608 // sockets, i.e., if it is the owner.
6609 final NetworkAgentInfo vpn = getVpnForUid(uid);
6610 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6611 && uid != vpn.networkCapabilities.getOwnerUid()) {
6612 return false;
6613 }
6614
6615 // The UID's permission must be at least sufficient for the network. Since the restricted
6616 // permission was already checked above, that just leaves background networks.
6617 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6618 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6619 }
6620
6621 // Unrestricted network. Anyone gets to use it.
6622 return true;
6623 }
6624
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006625 /**
6626 * Returns information about the proxy a certain network is using. If given a null network, it
6627 * it will return the proxy for the bound network for the caller app or the default proxy if
6628 * none.
6629 *
6630 * @param network the network we want to get the proxy information for.
6631 * @return Proxy information if a network has a proxy configured, or otherwise null.
6632 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006633 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006634 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006635 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006636 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006637 if (network == null) {
6638 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006639 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006640 true);
6641 if (activeNetwork == null) {
6642 return null;
6643 }
6644 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006645 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006646 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6647 // caller may not have.
6648 return getLinkPropertiesProxyInfo(network);
6649 }
6650 // No proxy info available if the calling UID does not have network access.
6651 return null;
6652 }
6653
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006654
6655 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006656 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6657 if (nai == null) return null;
6658 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006659 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6660 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006661 }
6662 }
6663
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006664 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006665 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006666 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006667 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006668 }
6669
Chalard Jean777e2e52018-06-07 18:02:37 +09006670 @Override
6671 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006672 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006673 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006674 }
6675
Aaron Huang9fe47be2021-06-08 13:11:45 +08006676 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006677 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006678 final NetworkAgentInfo nai = getDefaultNetwork();
6679 // TODO : this method should check that net == nai.network, unfortunately at this point
6680 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6681 // is only ever installed on the default network so in practice this is okay.
6682 if (null == nai) return;
6683 // PAC proxies only work on the default network. Therefore, only the default network
6684 // should have its link properties fixed up for PAC proxies.
6685 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6686 if (nai.everConnected()) {
6687 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6688 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006689 }
6690
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006691 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6692 // when any network changes proxy.
6693 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6694 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006695 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6696 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006697 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6698
Chalard Jean7d97afc2018-06-07 17:41:29 +09006699 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006700 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006701 }
6702 }
6703
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006704 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006705 final private HashMap<Uri, Integer> mUriEventMap;
6706 final private Context mContext;
6707 final private Handler mHandler;
6708
6709 SettingsObserver(Context context, Handler handler) {
6710 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006711 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006712 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006713 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006714 }
6715
Erik Kline05f2b402015-04-30 12:58:40 +09006716 void observe(Uri uri, int what) {
6717 mUriEventMap.put(uri, what);
6718 final ContentResolver resolver = mContext.getContentResolver();
6719 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006720 }
6721
6722 @Override
6723 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006724 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006725 }
6726
6727 @Override
6728 public void onChange(boolean selfChange, Uri uri) {
6729 final Integer what = mUriEventMap.get(uri);
6730 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006731 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006732 } else {
6733 loge("No matching event to send for URI=" + uri);
6734 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006735 }
6736 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006737
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006738 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006739 Log.d(TAG, s);
6740 }
6741
6742 private static void logw(String s) {
6743 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006744 }
6745
Daniel Brightf9e945b2020-06-15 16:10:01 -07006746 private static void logwtf(String s) {
6747 Log.wtf(TAG, s);
6748 }
6749
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006750 private static void logwtf(String s, Throwable t) {
6751 Log.wtf(TAG, s, t);
6752 }
6753
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006754 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006755 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006756 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006757
Hugo Benichi39621362017-02-11 17:04:43 +09006758 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006759 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006760 }
6761
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006762 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006763 * Return the information of all ongoing VPNs.
6764 *
6765 * <p>This method is used to update NetworkStatsService.
6766 *
6767 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006768 */
junyulai2050bed2021-01-23 09:46:34 +08006769 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006770 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006771 if (mLockdownEnabled) {
6772 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006773 }
junyulai2050bed2021-01-23 09:46:34 +08006774 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006775 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006776 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006777 if (info != null) {
6778 infoList.add(info);
6779 }
6780 }
junyulai2050bed2021-01-23 09:46:34 +08006781 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006782 }
6783
6784 /**
6785 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006786 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006787 */
junyulai2050bed2021-01-23 09:46:34 +08006788 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006789 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006790 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6791 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006792 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6793 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6794 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006795 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6796 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006797 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006798 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006799 }
6800 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006801
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006802 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006803
6804 List<String> interfaces = new ArrayList<>();
6805 for (Network network : underlyingNetworks) {
6806 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6807 if (underlyingNai == null) continue;
6808 LinkProperties lp = underlyingNai.linkProperties;
6809 for (String iface : lp.getAllInterfaceNames()) {
6810 if (!TextUtils.isEmpty(iface)) {
6811 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006812 }
6813 }
Benedict Wong34857f82019-06-12 17:46:15 +00006814 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006815
6816 if (interfaces.isEmpty()) return null;
6817
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006818 // Must be non-null or NetworkStatsService will crash.
6819 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6820 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006821 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006822 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006823
junyulai2050bed2021-01-23 09:46:34 +08006824 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6825 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006826 }
6827
James Mattisd31bdfa2020-12-23 16:37:26 -08006828 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006829 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6830 Network[] underlyingNetworks) {
6831 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006832 if (underlyingNetworks == null && defaultNetwork != null) {
6833 // null underlying networks means to track the default.
6834 underlyingNetworks = new Network[] { defaultNetwork };
6835 }
6836 return underlyingNetworks;
6837 }
6838
6839 // Returns true iff |network| is an underlying network of |nai|.
6840 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6841 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6842 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006843 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006844 final Network[] underlying = underlyingNetworksOrDefault(
6845 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006846 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006847 }
6848
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006849 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006850 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006851 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006852 * When underlying networks change, such networks may have to update capabilities to reflect
6853 * things like the metered bit, their transports, and so on. The capabilities are calculated
6854 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006855 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006856 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006857 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006858 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006859 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006860 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006861 }
6862 }
6863 }
6864
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006865 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6866 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6867 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6868 // a VPN is not up.
6869 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6870 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6871 for (UidRange range : blockedUidRanges) {
6872 if (range.contains(uid)) return true;
6873 }
6874 return false;
6875 }
6876
6877 @Override
6878 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006879 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006880 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6881 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6882 }
6883
6884 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6885 if (DBG) {
6886 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6887 + Arrays.toString(ranges));
6888 }
6889 // Cannot use a Set since the list of UID ranges might contain duplicates.
6890 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6891 for (int i = 0; i < ranges.length; i++) {
6892 if (requireVpn) {
6893 newVpnBlockedUidRanges.add(ranges[i]);
6894 } else {
6895 newVpnBlockedUidRanges.remove(ranges[i]);
6896 }
6897 }
6898
6899 try {
6900 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6901 } catch (RemoteException | ServiceSpecificException e) {
6902 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6903 + Arrays.toString(ranges) + "): netd command failed: " + e);
6904 }
6905
Chalard Jeandf29a852023-05-29 17:02:43 +09006906 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006907 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6908 }
6909
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006910 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6911 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006912 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6913 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006914 }
6915
6916 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6917 }
6918
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006919 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006920 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006921 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006922 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006923 }
6924
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006925 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6926 return mLockdownEnabled
6927 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6928 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006929 }
6930
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006931 private NetworkAgentInfo getLegacyLockdownNai() {
6932 if (!mLockdownEnabled) {
6933 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006934 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006935 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006936 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6937 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006938
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006939 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006940 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6941 // a local variable. There is no need to make a copy because its contents cannot change.
6942 final Network[] underlying = nai.declaredUnderlyingNetworks;
6943 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006944 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006945 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006946
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006947 // The legacy lockdown VPN always uses the default network.
6948 // If the VPN's underlying network is no longer the current default network, it means that
6949 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006950 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6951 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006952 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006953 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006954 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006955 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006956
6957 return nai;
6958 };
6959
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006960 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6961 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6962 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006963 private DetailedState getLegacyLockdownState(DetailedState origState) {
6964 if (origState != DetailedState.CONNECTED) {
6965 return origState;
6966 }
6967 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6968 ? DetailedState.CONNECTING
6969 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006970 }
6971
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006972 private void filterForLegacyLockdown(NetworkInfo ni) {
6973 if (!mLockdownEnabled || !ni.isConnected()) return;
6974 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6975 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6976 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6977 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6978 // network, this time with a state of CONNECTED.
6979 //
6980 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6981 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6982 // is not too far off the truth, since an always-on VPN, when not connected, is always
6983 // trying to reconnect.
6984 if (getLegacyLockdownNai() == null) {
6985 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6986 }
6987 }
6988
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006989 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006990 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006991 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006992 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006993 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6994 return;
6995 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006996 final long ident = Binder.clearCallingIdentity();
6997 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006998 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006999 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09007000 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04007001 } finally {
7002 Binder.restoreCallingIdentity(ident);
7003 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07007004 }
Wink Savillecb117d32013-08-29 14:57:08 -07007005
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007006 @Override
7007 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01007008 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007009 final long ident = Binder.clearCallingIdentity();
7010 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007011 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09007012 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007013 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
7014 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08007015 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007016 } finally {
7017 Binder.restoreCallingIdentity(ident);
7018 }
7019 }
7020
James Mattis02220e22021-03-13 19:27:21 -08007021 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08007022 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7023 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7024 }
Chalard Jeane0abd522023-01-23 16:47:43 +09007025 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007026 }
7027
James Mattis02220e22021-03-13 19:27:21 -08007028 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09007029 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007030 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08007031 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
7032 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09007033 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08007034 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7035 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7036 }
junyulaid91e7052020-08-28 13:44:33 +08007037 }
7038
James Mattis02220e22021-03-13 19:27:21 -08007039 private void onPackageChanged(@NonNull final String packageName) {
7040 // This is necessary in case a package is added or removed, but also when it's replaced to
7041 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
7042 // as one in the preferences, then it should follow the same routing as that other package,
7043 // which means updating the rules is never to be needed in this case (whether it joins or
7044 // leaves a UID with a preference).
7045 if (isMappedInOemNetworkPreference(packageName)) {
7046 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7047 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007048
7049 // Invalidates cache entry when the package is updated.
7050 synchronized (mSelfCertifiedCapabilityCache) {
7051 mSelfCertifiedCapabilityCache.remove(packageName);
7052 }
James Mattis02220e22021-03-13 19:27:21 -08007053 }
7054
7055 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007056 @Override
7057 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007058 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007059 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007060 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007061
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007062 // User should be filled for below intents, check the existence.
7063 if (user == null) {
7064 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7065 return;
7066 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007067
Lorenzo Colitticd675292021-02-04 17:32:07 +09007068 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007069 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007070 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007071 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007072 } else {
junyulaid91e7052020-08-28 13:44:33 +08007073 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007074 }
7075 }
7076 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007077
James Mattis02220e22021-03-13 19:27:21 -08007078 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7079 @Override
7080 public void onReceive(Context context, Intent intent) {
7081 ensureRunningOnConnectivityServiceThread();
7082 switch (intent.getAction()) {
7083 case Intent.ACTION_PACKAGE_ADDED:
7084 case Intent.ACTION_PACKAGE_REMOVED:
7085 case Intent.ACTION_PACKAGE_REPLACED:
7086 onPackageChanged(intent.getData().getSchemeSpecificPart());
7087 break;
7088 default:
7089 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7090 }
7091 }
7092 };
7093
Junyu Lai38c75032023-12-04 07:52:19 +00007094 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
7095 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
7096 @Override
7097 public void onReceive(Context context, Intent intent) {
7098 if (mDeps.isAtLeastV()) {
7099 throw new IllegalStateException(
7100 "data saver status should be updated from platform");
7101 }
7102 ensureRunningOnConnectivityServiceThread();
7103 switch (intent.getAction()) {
7104 case ACTION_RESTRICT_BACKGROUND_CHANGED:
7105 // If the uid is present in the deny list, the API will consistently
7106 // return ENABLED. To retrieve the global switch status, the system
7107 // uid is chosen because it will never be included in the deny list.
7108 final int dataSaverForSystemUid =
7109 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
7110 final boolean isDataSaverEnabled = (dataSaverForSystemUid
7111 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
7112 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
7113 break;
7114 default:
7115 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7116 }
7117 }
7118 };
7119
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007120 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007121 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007122
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007123 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007124 public final String name;
7125 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007126 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007127 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007128
lifraf3a3492021-03-10 13:58:14 +08007129 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7130 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007131 this.name = name;
7132 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007133 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007134 mDeathRecipient = deathRecipient;
7135
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007136 if (mDeathRecipient == null) {
7137 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007138 }
7139 }
7140
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007141 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007142 try {
7143 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7144 } catch (RemoteException e) {
7145 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007146 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007147 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007148 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007149
James Mattis4fce5d12020-11-12 15:53:42 -08007150 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7151 for (int i = 0; i < requests.size(); i++) {
7152 ensureNetworkRequestHasType(requests.get(i));
7153 }
7154 }
7155
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007156 private void ensureNetworkRequestHasType(NetworkRequest request) {
7157 if (request.type == NetworkRequest.Type.NONE) {
7158 throw new IllegalArgumentException(
7159 "All NetworkRequests in ConnectivityService must have a type");
7160 }
7161 }
7162
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007163 /**
7164 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007165 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007166 */
James Mattis258ea3c2020-11-15 15:04:40 -08007167 @VisibleForTesting
7168 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007169 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7170 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007171 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007172
James Mattisa076c532020-12-02 14:12:41 -08007173 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7174 void setSatisfier(
7175 @Nullable final NetworkAgentInfo satisfier,
7176 @Nullable final NetworkRequest activeRequest) {
7177 mSatisfier = satisfier;
7178 mActiveRequest = activeRequest;
7179 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007180
James Mattisd31bdfa2020-12-23 16:37:26 -08007181 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007182 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007183 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007184 private NetworkAgentInfo mSatisfier;
7185 NetworkAgentInfo getSatisfier() {
7186 return mSatisfier;
7187 }
7188
7189 // The request in mRequests assigned to a network agent. This is null if none of the
7190 // requests in mRequests can be satisfied. This member has the constraint of only being
7191 // accessible on the handler thread.
7192 @Nullable
7193 private NetworkRequest mActiveRequest;
7194 NetworkRequest getActiveRequest() {
7195 return mActiveRequest;
7196 }
7197
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007198 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007199 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007200 @Nullable
7201 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007202
7203 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007204 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007205 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007206 final int mPid;
7207 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007208 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007209 @Nullable
7210 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007211
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007212 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007213 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007214
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007215 // Effective UID of this request. This is different from mUid when a privileged process
7216 // files a request on behalf of another UID. This UID is used to determine blocked status,
7217 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7218 // maximum limit of registered callbacks per UID.
7219 final int mAsUid;
7220
paulhu48291862021-07-14 14:53:57 +08007221 // Preference order of this request.
7222 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007223
James Mattis3ce3d3c2021-02-09 18:18:28 -08007224 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7225 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7226 // maintained for keying off of. This is only a concern when the original nri
7227 // mNetworkRequests changes which happens currently for apps that register callbacks to
7228 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7229 // that match the per-app default nri that currently tracks the calling app's uid so that
7230 // callbacks are fired at the appropriate time. When the callbacks fire,
7231 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7232 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7233 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7234 @NonNull
7235 private final NetworkRequest mNetworkRequestForCallback;
7236 NetworkRequest getNetworkRequestForCallback() {
7237 return mNetworkRequestForCallback;
7238 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007239
James Mattisd31bdfa2020-12-23 16:37:26 -08007240 /**
7241 * Get the list of UIDs this nri applies to.
7242 */
7243 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007244 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007245 // networkCapabilities.getUids() returns a defensive copy.
7246 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007247 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7248 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007249 }
7250
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007251 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7252 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007253 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007254 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007255 }
7256
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007257 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007258 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007259 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007260 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007261 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007262 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007263 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007264 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007265 mBinder = null;
7266 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007267 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007268 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007269 mPerUidCounter = getRequestCounter(this);
7270 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007271 /**
7272 * Location sensitive data not included in pending intent. Only included in
7273 * {@link NetworkCallback}.
7274 */
7275 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007276 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007277 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007278 }
7279
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007280 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007281 @Nullable final IBinder binder,
7282 @NetworkCallback.Flag int callbackFlags,
7283 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007284 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7285 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007286 }
7287
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007288 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007289 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007290 @Nullable final IBinder binder,
7291 @NetworkCallback.Flag int callbackFlags,
7292 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007293 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007294 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007295 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007296 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007297 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007298 mBinder = binder;
7299 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007300 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007301 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007302 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007303 mPerUidCounter = getRequestCounter(this);
7304 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007305 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007306 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007307 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007308 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007309 }
7310
James Mattis3ce3d3c2021-02-09 18:18:28 -08007311 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7312 @NonNull final List<NetworkRequest> r) {
7313 super();
7314 ensureAllNetworkRequestsHaveType(r);
7315 mRequests = initializeRequests(r);
7316 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007317 final NetworkAgentInfo satisfier = nri.getSatisfier();
7318 if (null != satisfier) {
7319 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7320 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007321 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007322 // As this code creates a new NRI with a new set of requests, figure out which of
7323 // the list of requests should be the active request. It is always the first
7324 // request of the list that can be satisfied by the satisfier since the order of
7325 // requests is a priority order.
7326 // Note even in the presence of a satisfier there may not be an active request,
7327 // when the satisfier is the no-service network.
7328 NetworkRequest activeRequest = null;
7329 for (final NetworkRequest candidate : r) {
7330 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7331 activeRequest = candidate;
7332 break;
7333 }
7334 }
7335 setSatisfier(satisfier, activeRequest);
7336 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007337 mMessenger = nri.mMessenger;
7338 mBinder = nri.mBinder;
7339 mPid = nri.mPid;
7340 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007341 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007342 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007343 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007344 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007345 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007346 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007347 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007348 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007349 }
7350
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007351 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007352 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007353 }
7354
paulhue9913722021-05-26 15:19:20 +08007355 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007356 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007357 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007358 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007359 }
7360
James Mattis2516da32021-01-31 17:06:19 -08007361 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7362 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7363 // false.
7364 boolean isBeingSatisfied() {
7365 return (null != mSatisfier && null != mActiveRequest);
7366 }
7367
James Mattis3d229892020-11-16 16:46:28 -08007368 boolean isMultilayerRequest() {
7369 return mRequests.size() > 1;
7370 }
7371
James Mattis45d81842021-01-10 14:24:24 -08007372 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7373 // Creating a defensive copy to prevent the sender from modifying the list being
7374 // reflected in the return value of this method.
7375 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007376 return Collections.unmodifiableList(tempRequests);
7377 }
7378
James Mattisb1392002021-03-31 13:57:52 -07007379 void linkDeathRecipient() {
7380 if (null != mBinder) {
7381 try {
7382 mBinder.linkToDeath(this, 0);
7383 } catch (RemoteException e) {
7384 binderDied();
7385 }
7386 }
7387 }
7388
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007389 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007390 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007391 try {
7392 mBinder.unlinkToDeath(this, 0);
7393 } catch (NoSuchElementException e) {
7394 // Temporary workaround for b/194394697 pending analysis of additional logs
7395 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7396 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007397 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007398 }
7399
paulhu48291862021-07-14 14:53:57 +08007400 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7401 // Compare two preference orders.
7402 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007403 }
7404
paulhu48291862021-07-14 14:53:57 +08007405 int getPreferenceOrderForNetd() {
7406 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7407 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7408 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007409 }
paulhu48291862021-07-14 14:53:57 +08007410 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007411 }
7412
James Mattis4fce5d12020-11-12 15:53:42 -08007413 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007414 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007415 // As an immutable collection, mRequests cannot change by the time the
7416 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7417 // is acceptable. Use handleReleaseNetworkRequest and not directly
7418 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7419 // the app already unregistered the request.
7420 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7421 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007422 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007423
James Mattis4fce5d12020-11-12 15:53:42 -08007424 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007425 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007426 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7427 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007428 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007429 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007430 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007431 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007432 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007433 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007434 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007435 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007436 }
7437
Junyu Lai00d92df2022-07-05 11:01:52 +08007438 // Keep backward compatibility since the ServiceSpecificException is used by
7439 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7440 public static class RequestInfoPerUidCounter extends PerUidCounter {
7441 RequestInfoPerUidCounter(int maxCountPerUid) {
7442 super(maxCountPerUid);
7443 }
7444
7445 @Override
7446 public synchronized void incrementCountOrThrow(int uid) {
7447 try {
7448 super.incrementCountOrThrow(uid);
7449 } catch (IllegalStateException e) {
7450 throw new ServiceSpecificException(
7451 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7452 "Uid " + uid + " exceeded its allotted requests limit");
7453 }
7454 }
7455
7456 @Override
7457 public synchronized void decrementCountOrThrow(int uid) {
7458 throw new UnsupportedOperationException("Use decrementCount instead.");
7459 }
7460
7461 public synchronized void decrementCount(int uid) {
7462 try {
7463 super.decrementCountOrThrow(uid);
7464 } catch (IllegalStateException e) {
7465 logwtf("Exception when decrement per uid request count: ", e);
7466 }
7467 }
7468 }
7469
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007470 // This checks that the passed capabilities either do not request a
7471 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007472 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007473 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007474 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007475 throw new SecurityException("Insufficient permissions to request a specific SSID");
7476 }
paulhu1a407652019-03-22 16:35:06 +08007477
7478 if (nc.hasSignalStrength()
7479 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7480 throw new SecurityException(
7481 "Insufficient permissions to request a specific signal strength");
7482 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007483 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007484
junyulai2217bec2021-04-14 23:33:31 +08007485 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007486 enforceNetworkFactoryPermission();
7487 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007488 }
7489
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007490 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007491 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007492 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007493 // mNetworkRequests may contain the same value multiple times in case of
7494 // multilayer requests. It won't matter in this case because the thresholds
7495 // will then be the same and be deduplicated as they enter the `thresholds` set.
7496 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007497 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7498 for (final NetworkRequest req : nri.mRequests) {
7499 if (req.networkCapabilities.hasSignalStrength()
7500 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7501 thresholds.add(req.networkCapabilities.getSignalStrength());
7502 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007503 }
7504 }
7505 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007506 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007507 }
7508
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007509 private void updateSignalStrengthThresholds(
7510 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007511 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007512
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007513 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007514 String detail;
7515 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7516 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7517 } else {
7518 detail = reason;
7519 }
7520 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007521 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007522 }
7523
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007524 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007525 }
7526
Chalard Jeandd421992021-12-16 23:16:02 +09007527 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007528 if (nc == null) {
7529 return;
7530 }
7531 NetworkSpecifier ns = nc.getNetworkSpecifier();
7532 if (ns == null) {
7533 return;
7534 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007535 if (ns instanceof MatchAllNetworkSpecifier) {
7536 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7537 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007538 }
7539
Chalard Jeandd421992021-12-16 23:16:02 +09007540 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007541 ensureValidNetworkSpecifier(nc);
7542 if (nc.isPrivateDnsBroken()) {
7543 throw new IllegalArgumentException("Can't request broken private DNS");
7544 }
Chalard Jeande665262022-02-25 16:12:12 +09007545 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007546 throw new IllegalArgumentException("Can't request access UIDs");
7547 }
lucasline117e2e2019-10-22 18:27:33 +08007548 }
7549
Chalard Jeandd421992021-12-16 23:16:02 +09007550 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7551 ensureListenableCapabilities(nc);
7552 final String badCapability = nc.describeFirstNonRequestableCapability();
7553 if (badCapability != null) {
7554 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7555 }
7556 }
7557
Chiachang Wang3bc52762021-11-25 14:17:57 +08007558 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7559 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007560 private boolean isTargetSdkAtleast(int version, int callingUid,
7561 @NonNull String callingPackageName) {
7562 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007563 final PackageManager pm =
7564 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007565 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007566 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007567 if (callingVersion < version) return false;
7568 } catch (PackageManager.NameNotFoundException e) { }
7569 return true;
7570 }
7571
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007572 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007573 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007574 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007575 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007576 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007577 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007578 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7579 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007580 throw new SecurityException("Insufficient permissions to specify legacy type");
7581 }
markchienfac84a22020-03-18 21:16:15 +08007582 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007583 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007584 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007585 // Privileged callers can track the default network of another UID by passing in a UID.
7586 if (asUid != Process.INVALID_UID) {
7587 enforceSettingsPermission();
7588 } else {
7589 asUid = callingUid;
7590 }
junyulaiad010792021-01-11 16:53:38 +08007591 final NetworkRequest.Type reqType;
7592 try {
7593 reqType = NetworkRequest.Type.values()[reqTypeInt];
7594 } catch (ArrayIndexOutOfBoundsException e) {
7595 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7596 }
7597 switch (reqType) {
7598 case TRACK_DEFAULT:
7599 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007600 // is unused and will be replaced by ones appropriate for the UID (usually, the
7601 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007602 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007603 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007604 enforceAccessPermission();
7605 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007606 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007607 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007608 networkCapabilities = new NetworkCapabilities(defaultNc);
7609 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007610 case BACKGROUND_REQUEST:
7611 enforceNetworkStackOrSettingsPermission();
7612 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007613 case REQUEST:
7614 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7615 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007616 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007617 // TODO: this is incorrect. We mark the request as metered or not depending on
7618 // the state of the app when the request is filed, but we never change the
7619 // request if the app changes network state. http://b/29964605
7620 enforceMeteredApnPolicy(networkCapabilities);
7621 break;
junyulai1b1c8742021-03-12 20:05:08 +08007622 case LISTEN_FOR_BEST:
7623 enforceAccessPermission();
7624 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7625 break;
junyulaiad010792021-01-11 16:53:38 +08007626 default:
7627 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007628 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007629 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007630 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007631 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007632
junyulai1b1c8742021-03-12 20:05:08 +08007633 // Enforce FOREGROUND if the caller does not have permission to use background network.
7634 if (reqType == LISTEN_FOR_BEST) {
7635 restrictBackgroundRequestForCaller(networkCapabilities);
7636 }
7637
7638 // Set the UID range for this request to the single UID of the requester, unless the
7639 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007640 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7641 // are no visible methods to set the UIDs, an app could use reflection to try and get
7642 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007643 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007644 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7645 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007646
Etan Cohen85000162017-02-05 10:42:27 -08007647 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007648 throw new IllegalArgumentException("Bad timeout specified");
7649 }
Etan Cohen9786d922015-11-18 10:56:15 -08007650
James Mattis3ce3d3c2021-02-09 18:18:28 -08007651 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007652 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007653 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007654 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007655 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007656 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007657
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007658 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7659 // copied from the default request above. (This is necessary to ensure, for example, that
7660 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7661 // changes don't alter request matching.
7662 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7663 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007664 throw new IllegalStateException(
7665 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007666 + networkCapabilities + " vs. " + defaultNc);
7667 }
7668
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007669 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007670 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007671 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007672 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007673 }
7674 return networkRequest;
7675 }
7676
James Mattis3ce3d3c2021-02-09 18:18:28 -08007677 /**
7678 * Return the nri to be used when registering a network request. Specifically, this is used with
7679 * requests registered to track the default request. If there is currently a per-app default
7680 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7681 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007682 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7683 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007684 * @param nr the network request for the nri.
7685 * @param msgr the messenger for the nri.
7686 * @param binder the binder for the nri.
7687 * @param callingAttributionTag the calling attribution tag for the nri.
7688 * @return the nri to register.
7689 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007690 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007691 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007692 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007693 @Nullable String callingAttributionTag) {
7694 final List<NetworkRequest> requests;
7695 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7696 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007697 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007698 } else {
7699 requests = Collections.singletonList(nr);
7700 }
Roshan Pius951c0032020-12-22 15:10:42 -08007701 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007702 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007703 }
7704
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007705 private boolean shouldCheckCapabilitiesDeclaration(
7706 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7707 @NonNull final String callingPackageName) {
7708 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7709 // Only run the check if the change is enabled.
7710 if (!mDeps.isChangeEnabled(
7711 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7712 callingPackageName, user)) {
7713 return false;
7714 }
7715
7716 return networkCapabilities.hasCapability(
7717 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7718 || networkCapabilities.hasCapability(
7719 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7720 }
7721
7722 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007723 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007724 // This check is added to fix the linter error for "current min is 30", which is not going
7725 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007726 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007727 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7728 return;
7729 }
7730 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007731 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007732 try {
7733 synchronized (mSelfCertifiedCapabilityCache) {
7734 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7735 callerPackageName);
7736 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007737 final PackageManager packageManager =
7738 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
7739 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007740 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7741 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7742 callerPackageName
7743 );
7744 final XmlResourceParser parser = packageManager
7745 .getResourcesForApplication(callerPackageName)
7746 .getXml(networkSliceProperty.getResourceId());
7747 applicationNetworkCapabilities =
7748 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7749 mSelfCertifiedCapabilityCache.put(callerPackageName,
7750 applicationNetworkCapabilities);
7751 }
7752
7753 }
7754 } catch (PackageManager.NameNotFoundException ne) {
7755 throw new SecurityException(
7756 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7757 + " property");
7758 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7759 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007760 } finally {
7761 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007762 }
7763
7764 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7765 networkCapabilities);
7766 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007767 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007768 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007769 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7770 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007771 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
7772 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007773 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007774 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007775 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7776 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7777 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7778 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007779 }
junyulai96bd9fe2022-03-08 17:36:42 +08007780 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007781 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007782 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007783 }
7784 }
7785
fenglu3f357402015-03-20 11:29:56 -07007786 @Override
fenglub00f4882015-04-21 17:12:05 -07007787 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007788 enforceAccessPermission();
7789 NetworkAgentInfo nai = null;
7790 if (network == null) {
7791 return false;
7792 }
7793 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007794 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007795 }
7796 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007797 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007798 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007799 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007800 Integer uidReqs = mBandwidthRequests.get(uid);
7801 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007802 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007803 }
7804 mBandwidthRequests.put(uid, ++uidReqs);
7805 }
fenglu3f357402015-03-20 11:29:56 -07007806 return true;
7807 }
7808 return false;
7809 }
7810
Felipe Leme0a5ae422016-06-20 16:36:29 -07007811 private boolean isSystem(int uid) {
7812 return uid < Process.FIRST_APPLICATION_UID;
7813 }
fenglu3f357402015-03-20 11:29:56 -07007814
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007815 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007816 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007817 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007818 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007819 return;
7820 }
Hugo Benichi39621362017-02-11 17:04:43 +09007821 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7822 // Policy already enforced.
7823 return;
7824 }
paulhuaf50d7d2020-12-24 19:47:34 +08007825 final long ident = Binder.clearCallingIdentity();
7826 try {
7827 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7828 // If UID is restricted, don't allow them to bring up metered APNs.
7829 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7830 }
7831 } finally {
7832 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007833 }
7834 }
7835
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007836 @Override
7837 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007838 PendingIntent operation, @NonNull String callingPackageName,
7839 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007840 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007841 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007842 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007843 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007844 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007845 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007846 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007847 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007848 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007849 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7850 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007851
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007852 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007853 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007854 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7855 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007856 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007857 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7858 nri));
7859 return networkRequest;
7860 }
7861
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007862 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7863 mHandler.sendMessageDelayed(
7864 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007865 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007866 }
7867
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007868 @Override
7869 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007870 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007871 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007872 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007873 }
7874
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007875 // In order to implement the compatibility measure for pre-M apps that call
7876 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7877 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7878 // This ensures it has permission to do so.
7879 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7880 if (nc == null) {
7881 return false;
7882 }
7883 int[] transportTypes = nc.getTransportTypes();
7884 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7885 return false;
7886 }
7887 try {
7888 mContext.enforceCallingOrSelfPermission(
7889 android.Manifest.permission.ACCESS_WIFI_STATE,
7890 "ConnectivityService");
7891 } catch (SecurityException e) {
7892 return false;
7893 }
7894 return true;
7895 }
7896
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007897 @Override
7898 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007899 Messenger messenger, IBinder binder,
7900 @NetworkCallback.Flag int callbackFlags,
7901 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007902 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007903 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7904 enforceAccessPermission();
7905 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007906
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007907 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007908 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007909 Binder.getCallingPid(), callingUid, callingPackageName);
7910 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007911 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7912 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7913 // onLost and onAvailable callbacks when networks move in and out of the background.
7914 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7915 // can't request networks.
7916 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007917 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007918
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007919 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007920 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007921 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007922 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007923 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007924 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007925
7926 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7927 return networkRequest;
7928 }
7929
7930 @Override
7931 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007932 PendingIntent operation, @NonNull String callingPackageName,
7933 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007934 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007935 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007936 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7937 enforceAccessPermission();
7938 }
Chalard Jeandd421992021-12-16 23:16:02 +09007939 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007940 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007941 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007942 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007943 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007944
7945 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007946 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007947 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7948 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007949 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007950
WeiZhang1cc3f172021-06-03 19:02:04 -05007951 mHandler.sendMessage(mHandler.obtainMessage(
7952 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007953 }
7954
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007955 /** Returns the next Network provider ID. */
7956 public final int nextNetworkProviderId() {
7957 return mNextNetworkProviderId.getAndIncrement();
7958 }
7959
Erik Kline0c04b742016-07-07 16:50:58 +09007960 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007961 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007962 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007963 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007964 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007965 }
7966
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007967 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7968 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007969 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7970 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7971 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007972 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007973 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007974 return;
7975 }
7976
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007977 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7978 mNetworkProviderInfos.put(npi.messenger, npi);
7979 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007980 }
7981
7982 @Override
7983 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007984 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007985 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007986 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007987 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007988 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7989 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007990 }
7991
7992 @Override
7993 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007994 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007995 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007996 }
7997
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007998 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007999 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008000 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
8001 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09008002 Objects.requireNonNull(score);
8003 Objects.requireNonNull(caps);
8004 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008005 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008006 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09008007 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
8008 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008009 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
8010 }
8011
Chalard Jeanbb902a52021-08-18 01:35:19 +09008012 private void updateOfferScore(final NetworkOffer offer) {
8013 final boolean yieldToBadWiFi =
8014 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
8015 final NetworkOffer newOffer = new NetworkOffer(
8016 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
8017 offer.caps, offer.callback, offer.providerId);
8018 if (offer.equals(newOffer)) return;
8019 handleRegisterNetworkOffer(newOffer);
8020 }
8021
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008022 @Override
8023 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08008024 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008025 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
8026 }
8027
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008028 private void handleUnregisterNetworkProvider(Messenger messenger) {
8029 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
8030 if (npi == null) {
8031 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008032 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008033 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008034 // Unregister all the offers from this provider
8035 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
8036 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09008037 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008038 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
8039 toRemove.add(noi);
8040 }
8041 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09008042 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008043 handleUnregisterNetworkOffer(noi);
8044 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008045 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008046 }
8047
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008048 @Override
James Mattisf7027322020-12-13 16:28:14 -08008049 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008050 if (request.hasTransport(TRANSPORT_TEST)) {
8051 enforceNetworkFactoryOrTestNetworksPermission();
8052 } else {
8053 enforceNetworkFactoryPermission();
8054 }
James Mattisf7027322020-12-13 16:28:14 -08008055 final NetworkRequestInfo nri = mNetworkRequests.get(request);
8056 if (nri != null) {
8057 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
8058 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
8059 mHandler.post(() -> handleReleaseNetworkRequest(
8060 nri.mRequests.get(0), mDeps.getCallingUid(), true));
8061 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008062 }
8063
Paul Jensen1f567382015-02-13 14:18:39 -05008064 // NOTE: Accessed on multiple threads, must be synchronized on itself.
8065 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008066 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008067 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008068 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008069 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008070 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008071
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008072 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008073 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008074 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008075
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008076 // UID ranges for users that are currently blocked by VPNs.
8077 // This array is accessed and iterated on multiple threads without holding locks, so its
8078 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8079 // (on the handler thread).
8080 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8081
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008082 // Must only be accessed on the handler thread
8083 @NonNull
8084 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8085
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008086 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008087 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008088
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008089 // Current OEM network preferences. This object must only be written to on the handler thread.
8090 // Since it is immutable and always non-null, other threads may read it if they only care
8091 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008092 @NonNull
8093 private OemNetworkPreferences mOemNetworkPreferences =
8094 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008095 // Current per-profile network preferences. This object follows the same threading rules as
8096 // the OEM network preferences above.
8097 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008098 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8099 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008100
lucaslin3ba7cc22022-12-19 02:35:33 +00008101 // Current VPN network preferences. This object follows the same threading rules as the OEM
8102 // network preferences above.
8103 @NonNull
8104 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8105 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8106
paulhu51f77dc2021-06-07 02:34:20 +00008107 // A set of UIDs that should use mobile data preferentially if available. This object follows
8108 // the same threading rules as the OEM network preferences above.
8109 @NonNull
8110 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8111
James Mattiscb1e0362021-04-06 17:07:42 -07008112 // OemNetworkPreferences activity String log entries.
8113 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8114 @NonNull
8115 private final LocalLog mOemNetworkPreferencesLogs =
8116 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8117
James Mattis02220e22021-03-13 19:27:21 -08008118 /**
8119 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8120 * @param packageName the package name to check existence of a mapping for.
8121 * @return true if a mapping exists, false otherwise
8122 */
8123 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8124 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8125 }
8126
James Mattise3ef1912020-12-20 11:09:58 -08008127 // The always-on request for an Internet-capable network that apps without a specific default
8128 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008129 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008130 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008131 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008132 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008133 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008134 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008135 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008136
James Mattisd31bdfa2020-12-23 16:37:26 -08008137 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8138 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8139 }
8140
8141 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008142 * Return the default network request currently tracking the given uid.
8143 * @param uid the uid to check.
8144 * @return the NetworkRequestInfo tracking the given uid.
8145 */
8146 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008147 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008148 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008149 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008150 // Checking the first request is sufficient as only multilayer requests will have more
8151 // than one request and for multilayer, all requests will track the same uids.
8152 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008153 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008154 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008155 highestPriorityNri = nri;
8156 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008157 }
8158 }
paulhuaa0743d2021-05-26 21:56:03 +08008159 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008160 }
8161
8162 /**
8163 * Get a copy of the network requests of the default request that is currently tracking the
8164 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008165 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8166 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008167 * @param requestorUid the uid to check the default for.
8168 * @param requestorPackageName the requestor's package name.
8169 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8170 */
8171 @NonNull
8172 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008173 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008174 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008175 getDefaultRequestTrackingUid(asUid).mRequests,
8176 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008177 }
8178
8179 /**
8180 * Copy the given nri's NetworkRequest collection.
8181 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008182 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8183 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008184 * @param requestorUid the uid to set on the copied collection.
8185 * @param requestorPackageName the package name to set on the copied collection.
8186 * @return the copied NetworkRequest collection.
8187 */
8188 @NonNull
8189 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008190 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8191 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008192 final List<NetworkRequest> requests = new ArrayList<>();
8193 for (final NetworkRequest nr : requestsToCopy) {
8194 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008195 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008196 nr.legacyType, nextNetworkRequestId(), nr.type));
8197 }
8198 return requests;
8199 }
8200
8201 @NonNull
8202 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008203 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8204 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008205 // These capabilities are for a TRACK_DEFAULT callback, so:
8206 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8207 // mDefaultRequest and a per-UID default request.
8208 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008209 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008210 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008211 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8212 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008213 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008214 restrictRequestUidsForCallerAndSetRequestorInfo(
8215 netCap, requestorUid, requestorPackageName);
8216 return netCap;
8217 }
8218
8219 /**
8220 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8221 * @param nr the network request to check for equality against.
8222 * @return the nri if one exists, null otherwise.
8223 */
8224 @Nullable
8225 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8226 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8227 if (nri.getNetworkRequestForCallback().equals(nr)) {
8228 return nri;
8229 }
8230 }
8231 return null;
8232 }
8233
8234 /**
8235 * Check if an nri is currently being managed by per-app default networking.
8236 * @param nri the nri to check.
8237 * @return true if this nri is currently being managed by per-app default networking.
8238 */
8239 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8240 // nri.mRequests.get(0) is only different from the original request filed in
8241 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8242 // functionality therefore if these two don't match, it means this particular nri is
8243 // currently being managed by a per-app default.
8244 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8245 }
8246
8247 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008248 * Determine if an nri is a managed default request that disallows default networking.
8249 * @param nri the request to evaluate
8250 * @return true if device-default networking is disallowed
8251 */
8252 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8253 // Check if this nri is a managed default that supports the default network at its
8254 // lowest priority request.
8255 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8256 final NetworkCapabilities lowestPriorityNetCap =
8257 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8258 return isPerAppDefaultRequest(nri)
8259 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8260 lowestPriorityNetCap));
8261 }
8262
Erik Kline05f2b402015-04-30 12:58:40 +09008263 // Request used to optionally keep mobile data active even when higher
8264 // priority networks like Wi-Fi are active.
8265 private final NetworkRequest mDefaultMobileDataRequest;
8266
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008267 // Request used to optionally keep wifi data active even when higher
8268 // priority networks like ethernet are active.
8269 private final NetworkRequest mDefaultWifiRequest;
8270
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008271 // Request used to optionally keep vehicle internal network always active
8272 private final NetworkRequest mDefaultVehicleRequest;
8273
James Mattisd31bdfa2020-12-23 16:37:26 -08008274 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8275 // network with no service. This NAI should never be matched against, nor should any public API
8276 // ever return the associated network. For this reason, this NAI is not in the list of available
8277 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8278 // default requests that don't support using the device default network which will ultimately
8279 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8280 @VisibleForTesting
8281 final NetworkAgentInfo mNoServiceNetwork;
8282
Chalard Jean5b409c72021-02-04 13:12:59 +09008283 // The NetworkAgentInfo currently satisfying the default request, if any.
8284 private NetworkAgentInfo getDefaultNetwork() {
8285 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008286 }
8287
James Mattis2516da32021-01-31 17:06:19 -08008288 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008289 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008290 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8291 // Currently, all network requests will have the same uids therefore checking the first
8292 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008293 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008294 if (null == uids) {
8295 continue;
8296 }
8297 for (final UidRange range : uids) {
8298 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008299 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008300 highestPriorityNri = nri;
8301 }
James Mattis2516da32021-01-31 17:06:19 -08008302 }
8303 }
8304 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008305 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008306 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008307 }
8308
Varun Ananddf569952019-02-06 10:13:38 -08008309 @Nullable
8310 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8311 return nai != null ? nai.network : null;
8312 }
8313
8314 private void ensureRunningOnConnectivityServiceThread() {
8315 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8316 throw new IllegalStateException(
8317 "Not running on ConnectivityService thread: "
8318 + Thread.currentThread().getName());
8319 }
8320 }
8321
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008322 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008323 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8324 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008325 }
8326
Chalard Jean29d06db2018-05-02 21:14:54 +09008327 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008328 * Returns whether local agents are supported on this device.
8329 *
8330 * Local agents are supported from U on TVs, and from V on all devices.
8331 */
8332 @VisibleForTesting
8333 public boolean areLocalAgentsSupported() {
8334 final PackageManager pm = mContext.getPackageManager();
8335 // Local agents are supported starting on U on TVs and on V on everything else.
8336 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8337 }
8338
8339 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008340 * Register a new agent with ConnectivityService to handle a network.
8341 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008342 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008343 * @param networkInfo the initial info associated with this network. It can be updated later :
8344 * see {@link #updateNetworkInfo}.
8345 * @param linkProperties the initial link properties of this network. They can be updated
8346 * later : see {@link #updateLinkProperties}.
8347 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008348 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008349 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008350 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008351 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008352 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008353 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008354 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008355 public Network registerNetworkAgent(INetworkAgent na,
8356 NetworkInfo networkInfo,
8357 LinkProperties linkProperties,
8358 NetworkCapabilities networkCapabilities,
8359 @NonNull NetworkScore initialScore,
8360 @Nullable LocalNetworkConfig localNetworkConfig,
8361 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008362 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008363 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8364 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8365 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008366 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008367 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008368 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008369 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008370 } else {
8371 enforceNetworkFactoryPermission();
8372 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008373 final boolean hasLocalCap =
8374 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8375 if (hasLocalCap && !areLocalAgentsSupported()) {
8376 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8377 throw new IllegalArgumentException("Local agents are not supported in this version");
8378 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008379 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8380 if (hasLocalCap != hasLocalNetworkConfig) {
8381 throw new IllegalArgumentException(null != localNetworkConfig
8382 ? "Only local network agents can have a LocalNetworkConfig"
8383 : "Local network agents must have a LocalNetworkConfig"
8384 );
8385 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008386
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008387 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008388 final long token = Binder.clearCallingIdentity();
8389 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008390 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008391 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8392 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008393 } finally {
8394 Binder.restoreCallingIdentity(token);
8395 }
8396 }
8397
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008398 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008399 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008400 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8401 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008402 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008403
Chalard Jeandbc46952022-02-02 00:14:18 +09008404 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8405 // and mutate them at any time.
8406 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8407 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8408 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008409 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008410
Chalard Jean366c5252022-01-25 18:27:53 +09008411 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008412 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008413 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8414 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008415 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008416 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008417 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8418 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8419 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008420
Chalard Jeandbc46952022-02-02 00:14:18 +09008421 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008422 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008423 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008424 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008425 mDeps.getNetworkStack().makeNetworkMonitor(
8426 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008427 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8428 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008429 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008430 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008431 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008432 }
8433
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008434 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008435 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008436 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008437 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008438 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008439 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8440 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8441 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008442
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008443 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008444
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008445 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008446 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008447 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008448 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008449
8450 try {
8451 networkMonitor.start();
8452 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008453 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008454 }
Chalard Jean366c5252022-01-25 18:27:53 +09008455
Chalard Jean1e4c2182023-10-06 18:45:53 +09008456 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008457 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008458 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008459 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008460 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008461 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008462 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008463 }
8464
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008465 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8466 @NonNull public final NetworkOffer offer;
8467
8468 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8469 this.offer = offer;
8470 }
8471
8472 @Override
8473 public void binderDied() {
8474 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8475 }
8476 }
8477
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008478 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8479 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8480 if (npi.providerId == providerId) return true;
8481 }
8482 return false;
8483 }
8484
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008485 /**
8486 * Register or update a network offer.
8487 * @param newOffer The new offer. If the callback member is the same as an existing
8488 * offer, it is an update of that offer.
8489 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008490 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008491 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8492 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008493 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008494 // This may actually happen if a provider updates its score or registers and then
8495 // immediately unregisters. The offer would still be in the handler queue, but the
8496 // provider would have been removed.
8497 if (DBG) log("Received offer from an unregistered provider");
8498 return;
8499 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008500 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8501 if (null != existingOffer) {
8502 handleUnregisterNetworkOffer(existingOffer);
8503 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008504 if (DBG) {
8505 // handleUnregisterNetworkOffer has already logged the old offer
8506 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8507 }
8508 } else {
8509 if (DBG) {
8510 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8511 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008512 }
8513 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8514 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008515 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008516 } catch (RemoteException e) {
8517 noi.binderDied();
8518 return;
8519 }
8520 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008521 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008522 }
8523
8524 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8525 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008526 if (DBG) {
8527 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8528 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008529
8530 // If the provider removes the offer and dies immediately afterwards this
8531 // function may be called twice in a row, but the array will no longer contain
8532 // the offer.
8533 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008534 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008535 }
8536
8537 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8538 @NonNull final INetworkOfferCallback callback) {
8539 ensureRunningOnConnectivityServiceThread();
8540 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008541 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008542 }
8543 return null;
8544 }
8545
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008546 /**
8547 * Called when receiving LinkProperties directly from a NetworkAgent.
8548 * Stores into |nai| any data coming from the agent that might also be written to the network's
8549 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8550 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008551 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008552 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008553 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8554 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008555 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008556 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008557 }
8558
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008559 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008560 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008561 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008562
Lorenzo Colittid523d142020-04-01 20:16:30 +09008563 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8564 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8565 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008566 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008567
Suprabh Shukla1e312032023-01-24 03:36:37 -08008568 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008569
8570 // update filtering rules, need to happen after the interface update so netd knows about the
8571 // new interface (the interface name -> index map becomes initialized)
8572 updateVpnFiltering(newLp, oldLp, networkAgent);
8573
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008574 updateMtu(newLp, oldLp);
8575 // TODO - figure out what to do for clat
8576// for (LinkProperties lp : newLp.getStackedLinks()) {
8577// updateMtu(lp, null);
8578// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008579 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008580 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008581 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8582 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008583
Erik Klineb9888902016-04-05 13:30:49 +09008584 updateRoutes(newLp, oldLp, netId);
8585 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008586 // Make sure LinkProperties represents the latest private DNS status.
8587 // This does not need to be done before updateDnses because the
8588 // LinkProperties are not the source of the private DNS configuration.
8589 // updateDnses will fetch the private DNS configuration from DnsManager.
8590 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008591
Chalard Jean5b409c72021-02-04 13:12:59 +09008592 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008593 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008594 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008595 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008596 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008597
8598 updateWakeOnLan(newLp);
8599
Hai Shalome58bdc62021-01-11 18:45:34 -08008600 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8601 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8602 // does, it needs to be merged here.
8603 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8604 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008605
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008606 // TODO - move this check to cover the whole function
8607 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008608 synchronized (networkAgent) {
8609 networkAgent.linkProperties = newLp;
8610 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008611 // Start or stop DNS64 detection and 464xlat according to network state.
8612 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008613 // Notify NSS when relevant events happened. Currently, NSS only cares about
8614 // interface changed to update clat interfaces accounting.
8615 final boolean interfacesChanged = oldLp == null
8616 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8617 if (interfacesChanged) {
8618 notifyIfacesChangedForNetworkStats();
8619 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008620 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8621 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008622 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008623 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008624
8625 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008626 }
8627
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008628 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8629 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8630 }
8631
Hai Shalome58bdc62021-01-11 18:45:34 -08008632 /**
8633 * @param naData captive portal data from NetworkAgent
8634 * @param apiData captive portal data from capport API
8635 */
8636 @Nullable
8637 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8638 CaptivePortalData apiData) {
8639 if (naData == null || apiData == null) {
8640 return naData == null ? apiData : naData;
8641 }
8642 final CaptivePortalData.Builder captivePortalBuilder =
8643 new CaptivePortalData.Builder(naData);
8644
8645 if (apiData.isCaptive()) {
8646 captivePortalBuilder.setCaptive(true);
8647 }
8648 if (apiData.isSessionExtendable()) {
8649 captivePortalBuilder.setSessionExtendable(true);
8650 }
8651 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8652 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8653 // otherwise data would be inconsistent. Prefer the capport API info if present,
8654 // as it can generally be refreshed more often.
8655 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8656 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8657 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8658 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8659 // No source has time / bytes remaining information: surface the newest refresh time
8660 // for other fields
8661 captivePortalBuilder.setRefreshTime(
8662 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8663 }
8664
Hai Shalom7c6ab402021-02-04 19:34:06 -08008665 // Prioritize the user portal URL from the network agent if the source is authenticated.
8666 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8667 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8668 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8669 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008670 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008671 // Prioritize the venue information URL from the network agent if the source is
8672 // authenticated.
8673 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8674 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8675 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8676 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008677 }
8678 return captivePortalBuilder.build();
8679 }
8680
Suprabh Shukla53e16392023-04-26 18:47:36 -07008681 @VisibleForTesting
8682 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008683 // This needs to be kept in sync and backwards compatible with the decoding logic in
8684 // NetdEventListenerService, which is non-mainline code.
8685 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8686 }
8687
Suprabh Shukla75642282023-04-25 23:15:43 -07008688 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8689 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8690 return true;
8691 }
8692 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8693 return true;
8694 }
8695 return false;
8696 }
8697
Suprabh Shukla1e312032023-01-24 03:36:37 -08008698 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008699 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008700 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008701 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008702 return;
8703 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008704
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008705 // Mask/mark of zero will not detect anything interesting.
8706 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008707 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008708 return;
8709 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008710
Suprabh Shukla1e312032023-01-24 03:36:37 -08008711 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008712 try {
8713 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008714 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008715 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008716 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008717 }
8718 } catch (Exception e) {
8719 loge("Exception modifying wakeup packet monitoring: " + e);
8720 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008721 }
8722
Junyu Lai970963e2022-10-25 15:46:47 +08008723 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008724 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008725 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008726 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008727 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008728 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008729 for (final String iface : interfaceDiff.added) {
8730 try {
8731 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008732 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008733 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008734 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008735 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008736 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008737 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008738 }
Paul Jensenbff73492014-04-28 10:33:11 -04008739 }
8740 }
Chalard Jean9589e722019-11-19 19:03:53 +09008741 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008742 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008743 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008744 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008745 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008746 } catch (Exception e) {
8747 loge("Exception removing interface: " + e);
8748 }
8749 }
8750 }
8751
Paul Jensene0fd4a82014-08-06 15:51:33 -04008752 /**
8753 * Have netd update routes from oldLp to newLp.
8754 * @return true if routes changed between oldLp and newLp
8755 */
Junyu Lai970963e2022-10-25 15:46:47 +08008756 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8757 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008758 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008759 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8760 new CompareOrUpdateResult<>(
8761 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008762 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008763 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008764
8765 // add routes before removing old in case it helps with continuous connectivity
8766
Chalard Jean9dd11612018-06-04 16:52:49 +09008767 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008768 for (RouteInfo route : routeDiff.added) {
8769 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008770 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008771 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008772 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008773 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008774 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008775 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008776 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008777 }
8778 }
8779 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008780 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008781 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008782 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008783 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008784 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008785 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008786 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008787 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008788 }
8789 }
8790
8791 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008792 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008793 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008794 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008795 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008796 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008797 }
8798 }
Tyler Weare4314862019-12-05 14:55:30 -08008799
8800 for (RouteInfo route : routeDiff.updated) {
8801 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8802 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008803 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008804 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008805 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008806 }
8807 }
8808 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8809 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008810 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008811
Junyu Lai970963e2022-10-25 15:46:47 +08008812 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8813 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008814 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8815 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008816 }
Erik Klineb9888902016-04-05 13:30:49 +09008817
Erik Kline31b4a9e2018-01-11 21:07:29 +09008818 if (DBG) {
8819 final Collection<InetAddress> dnses = newLp.getDnsServers();
8820 log("Setting DNS servers for network " + netId + " to " + dnses);
8821 }
Erik Klineb9888902016-04-05 13:30:49 +09008822 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008823 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008824 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008825 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008826 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008827 }
Erik Kline54e35c02017-04-07 15:29:29 +09008828 }
8829
Junyu Lai970963e2022-10-25 15:46:47 +08008830 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8831 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008832 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8833 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008834 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8835 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008836
8837 if (!wasFiltering && !needsFiltering) {
8838 // Nothing to do.
8839 return;
8840 }
8841
8842 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8843 // Nothing changed.
8844 return;
8845 }
8846
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008847 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008848 if (ranges == null || ranges.isEmpty()) {
8849 return;
8850 }
8851
Qingxi Libb8da982020-01-17 17:54:27 -08008852 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008853 // TODO: this create a window of opportunity for apps to receive traffic between the time
8854 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008855 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008856 // old rules are being removed.
8857 if (wasFiltering) {
8858 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8859 }
8860 if (needsFiltering) {
8861 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8862 }
8863 }
8864
Valentin Iftime9fa35092019-09-24 13:32:13 +02008865 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008866 if (mWolSupportedInterfaces == null) {
8867 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008868 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008869 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008870 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8871 }
8872
Luke Huangb913c812018-08-24 20:33:16 +08008873 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008874 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008875 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008876 }
8877 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008878 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008879 }
Luke Huangb913c812018-08-24 20:33:16 +08008880 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008881 }
8882
Chalard Jean62edfd82019-12-02 18:39:29 +09008883 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8884 @NonNull final NetworkCapabilities newNc) {
8885 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8886 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008887 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008888 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008889 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008890 } catch (RemoteException | ServiceSpecificException e) {
8891 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008892 }
8893 }
8894 }
8895
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008896 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008897 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008898 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008899 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008900 underlyingNetworks = underlyingNetworksOrDefault(
8901 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008902 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008903 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8904 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008905 // metered if any underlying is metered, or originally declared metered by the agent.
8906 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008907 boolean roaming = false; // roaming if any underlying is roaming
8908 boolean congested = false; // congested if any underlying is congested
8909 boolean suspended = true; // suspended if all underlying are suspended
8910
8911 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008912 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008913 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008914 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008915 for (Network underlyingNetwork : underlyingNetworks) {
8916 final NetworkAgentInfo underlying =
8917 getNetworkAgentInfoForNetwork(underlyingNetwork);
8918 if (underlying == null) continue;
8919
8920 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8921 hadUnderlyingNetworks = true;
8922 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008923 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008924 }
8925
8926 // Merge capabilities of this underlying network. For bandwidth, assume the
8927 // worst case.
8928 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8929 underlyingCaps.getLinkDownstreamBandwidthKbps());
8930 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8931 underlyingCaps.getLinkUpstreamBandwidthKbps());
8932 // If this underlying network is metered, the VPN is metered (it may cost money
8933 // to send packets on this network).
8934 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8935 // If this underlying network is roaming, the VPN is roaming (the billing structure
8936 // is different than the usual, local one).
8937 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8938 // If this underlying network is congested, the VPN is congested (the current
8939 // condition of the network affects the performance of this network).
8940 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8941 // If this network is not suspended, the VPN is not suspended (the VPN
8942 // is able to transfer some data).
8943 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008944 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008945 }
8946 }
8947 if (!hadUnderlyingNetworks) {
8948 // No idea what the underlying networks are; assume reasonable defaults
8949 metered = true;
8950 roaming = false;
8951 congested = false;
8952 suspended = false;
8953 }
8954
Chalard Jean1d420b32022-10-12 16:39:37 +09008955 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008956 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8957 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8958 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8959 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8960 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8961 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008962 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008963 }
8964
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008965 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008966 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8967 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8968 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008969 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008970 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008971 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008972 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008973 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8974 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008975 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008976 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008977 if (nai.everConnected()
8978 && !nai.isVPN()
8979 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008980 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008981 // does not cause any request (that is not a listen) currently matching that agent to
8982 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008983 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008984 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008985 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008986 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008987 }
8988
Paul Jensen53f08952015-06-16 14:27:36 -04008989 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008990 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008991 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008992 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008993 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008994 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008995 }
Chalard Jean254bd162022-08-25 13:04:51 +09008996 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008997 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008998 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008999 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009000 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009001 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009002 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009003 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009004 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009005 }
Chalard Jean254bd162022-08-25 13:04:51 +09009006 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08009007 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9008 } else {
9009 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9010 }
lucasline117e2e2019-10-22 18:27:33 +08009011 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009012
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009013 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09009014 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
9015 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009016 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09009017 }
9018
Lorenzo Colittibd079452021-07-02 11:47:57 +09009019 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09009020 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09009021 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009022 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009023 }
9024
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009025 return newNc;
9026 }
9027
Lorenzo Colitti44840702021-01-11 22:27:57 +09009028 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
9029 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
9030 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9031 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9032 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9033 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9034 if (prevSuspended != suspended) {
9035 // TODO (b/73132094) : remove this call once the few users of onSuspended and
9036 // onResumed have been removed.
9037 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
9038 : ConnectivityManager.CALLBACK_RESUMED);
9039 }
9040 if (prevSuspended != suspended || prevRoaming != roaming) {
9041 // updateNetworkInfo will mix in the suspended info from the capabilities and
9042 // take appropriate action for the network having possibly changed state.
9043 updateNetworkInfo(nai, nai.networkInfo);
9044 }
9045 }
9046
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009047 /**
9048 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
9049 *
9050 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
9051 * capabilities we manage and store in {@code nai}, such as validated status and captive
9052 * portal status)
9053 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
9054 * potentially triggers rematches.
9055 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
9056 * change.)
9057 *
9058 * @param oldScore score of the network before any of the changes that prompted us
9059 * to call this function.
9060 * @param nai the network having its capabilities updated.
9061 * @param nc the new network capabilities.
9062 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009063 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09009064 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009065 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009066 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009067 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9068 if (null != differences) {
9069 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9070 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009071 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009072 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009073
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009074 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009075 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009076 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009077
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009078 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009079 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9080 // the change we're processing can't affect any requests, it can only affect the listens
9081 // on this network. We might have been called by rematchNetworkAndRequests when a
9082 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009083 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009084 } else {
9085 // If the requestable capabilities have changed or the score changed, we can't have been
9086 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009087 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009088 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009089 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009090 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009091
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009092 final boolean oldMetered = prevNc.isMetered();
9093 final boolean newMetered = newNc.isMetered();
9094 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009095
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009096 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009097 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9098 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009099 }
junyulaif2c67e42018-08-07 19:50:45 +08009100
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009101 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9102 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009103
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009104 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009105 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009106 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009107 }
9108
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009109 // This network might have been underlying another network. Propagate its capabilities.
9110 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009111
Ken Chen5a35cf92023-10-07 07:54:22 +08009112 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009113 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009114 }
lucaslin53e8a262021-06-08 01:43:59 +08009115
9116 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009117 }
9118
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009119 /** Convenience method to update the capabilities for a given network. */
9120 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009121 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009122 }
9123
Yang Sun29037f62023-12-04 10:31:58 +08009124 private void maybeApplyMulticastRoutingConfig(@NonNull final NetworkAgentInfo nai,
9125 final LocalNetworkConfig oldConfig,
9126 final LocalNetworkConfig newConfig) {
9127 final MulticastRoutingConfig oldUpstreamConfig =
9128 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9129 oldConfig.getUpstreamMulticastRoutingConfig();
9130 final MulticastRoutingConfig oldDownstreamConfig =
9131 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9132 oldConfig.getDownstreamMulticastRoutingConfig();
9133 final MulticastRoutingConfig newUpstreamConfig =
9134 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9135 newConfig.getUpstreamMulticastRoutingConfig();
9136 final MulticastRoutingConfig newDownstreamConfig =
9137 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9138 newConfig.getDownstreamMulticastRoutingConfig();
9139
9140 if (oldUpstreamConfig.equals(newUpstreamConfig) &&
9141 oldDownstreamConfig.equals(newDownstreamConfig)) {
9142 return;
9143 }
9144
9145 final String downstreamNetworkName = nai.linkProperties.getInterfaceName();
9146 final LocalNetworkInfo lni = localNetworkInfoForNai(nai);
9147 final Network upstreamNetwork = lni.getUpstreamNetwork();
9148
9149 if (upstreamNetwork != null) {
9150 final String upstreamNetworkName =
9151 getLinkProperties(upstreamNetwork).getInterfaceName();
9152 applyMulticastRoutingConfig(downstreamNetworkName, upstreamNetworkName, newConfig);
9153 }
9154 }
9155
9156 private void applyMulticastRoutingConfig(@NonNull String localNetworkInterfaceName,
9157 @NonNull String upstreamNetworkInterfaceName,
9158 @NonNull final LocalNetworkConfig config) {
Yang Sunca537d52024-01-19 12:53:50 +08009159 if (mMulticastRoutingCoordinatorService == null) {
9160 if (config.getDownstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE ||
9161 config.getUpstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE) {
9162 loge("Multicast routing is not supported, failed to configure " + config
9163 + " for " + localNetworkInterfaceName + " to "
9164 + upstreamNetworkInterfaceName);
9165 }
9166 return;
9167 }
Yang Sun29037f62023-12-04 10:31:58 +08009168
9169 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9170 upstreamNetworkInterfaceName, config.getUpstreamMulticastRoutingConfig());
9171 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9172 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9173 config.getDownstreamMulticastRoutingConfig());
9174 }
9175
9176 private void disableMulticastRouting(@NonNull String localNetworkInterfaceName,
9177 @NonNull String upstreamNetworkInterfaceName) {
Yang Sunca537d52024-01-19 12:53:50 +08009178 if (mMulticastRoutingCoordinatorService == null) {
9179 return;
9180 }
Yang Sun29037f62023-12-04 10:31:58 +08009181
9182 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9183 upstreamNetworkInterfaceName, MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9184 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9185 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9186 MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9187 }
9188
Chalard Jean1e4c2182023-10-06 18:45:53 +09009189 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009190 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009191 @Nullable final LocalNetworkConfig oldConfig,
9192 @NonNull final LocalNetworkConfig newConfig) {
9193 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009194 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9195 return;
9196 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009197
Chalard Jean4fe23392023-10-17 23:02:27 +09009198 if (VDBG) {
9199 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9200 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009201 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
Chalard Jean1e4c2182023-10-06 18:45:53 +09009202 configBuilder.setUpstreamMulticastRoutingConfig(
9203 newConfig.getUpstreamMulticastRoutingConfig());
9204 configBuilder.setDownstreamMulticastRoutingConfig(
9205 newConfig.getDownstreamMulticastRoutingConfig());
9206
9207 final NetworkRequest oldRequest =
9208 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9209 final NetworkCapabilities oldCaps =
9210 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9211 final NetworkRequestInfo oldNri =
9212 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9213 final NetworkAgentInfo oldSatisfier =
9214 null == oldNri ? null : oldNri.getSatisfier();
9215 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9216 final NetworkCapabilities newCaps =
9217 (null == newRequest) ? null : newRequest.networkCapabilities;
9218 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9219 if (null != oldRequest && requestUpdated) {
9220 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9221 if (null == newRequest && null != oldSatisfier) {
9222 // If there is an old satisfier, but no new request, then remove the old upstream.
9223 removeLocalNetworkUpstream(nai, oldSatisfier);
9224 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009225 // When there is a new request, the rematch sees the new request and sends the
9226 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9227 // But here there is no new request, so the rematch won't see anything. Send
9228 // callbacks to apps now to tell them about the loss of upstream.
9229 notifyNetworkCallbacks(nai,
9230 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009231 return;
9232 }
9233 }
9234 if (null != newRequest && requestUpdated) {
9235 // File the new request if :
9236 // - it has changed (requestUpdated), or
9237 // - it's the first time this local info (null == oldConfig)
9238 // is updated and the request has not been filed yet.
9239 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9240 // upstream (the best) but never request it to be brought up.
9241 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9242 nextNetworkRequestId(), LISTEN_FOR_BEST);
9243 configBuilder.setUpstreamSelector(nr);
9244 final NetworkRequestInfo nri = new NetworkRequestInfo(
9245 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9246 0 /* callbackFlags */, null /* attributionTag */);
9247 if (null != oldSatisfier) {
9248 // Set the old satisfier in the new NRI so that the rematch will see any changes
9249 nri.setSatisfier(oldSatisfier, nr);
9250 }
9251 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009252 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9253 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9254 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009255 handleRegisterNetworkRequest(nri);
9256 } else {
9257 configBuilder.setUpstreamSelector(oldRequest);
9258 nai.localNetworkConfig = configBuilder.build();
9259 }
Yang Sun29037f62023-12-04 10:31:58 +08009260 maybeApplyMulticastRoutingConfig(nai, oldConfig, newConfig);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009261 }
9262
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009263 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009264 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009265 *
9266 * Ingress interface filtering enforces that all apps under the given network can only receive
9267 * packets from the network's interface (and loopback). This is important for VPNs because
9268 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9269 * non-VPN interfaces.
9270 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009271 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009272 * 1. the network is an app VPN (not legacy VPN)
9273 * 2. the VPN does not allow bypass
9274 * 3. the VPN is fully-routed
9275 * 4. the VPN interface is non-null
9276 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009277 * @see INetd#firewallAddUidInterfaceRules
9278 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009279 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009280 @Nullable
9281 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009282 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009283 if (nc == null || lp == null) return null;
9284 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009285 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009286 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009287 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009288 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009289 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009290 && !lp.hasExcludeRoute()) {
9291 return lp.getInterfaceName();
9292 }
9293 return null;
9294 }
9295
9296 /**
9297 * Returns whether we need to set interface filtering rule or not
9298 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009299 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009300 String isolationIface) {
9301 // Allow rules are always needed if VPN isolation is enabled.
9302 if (isolationIface != null) return true;
9303
9304 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9305 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9306 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009307 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009308 }
9309
Chiachang Wang28afaff2020-12-10 22:24:47 +08009310 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9311 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9312 int index = 0;
9313 for (UidRange range : ranges) {
9314 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9315 index++;
9316 }
9317 return stableRanges;
9318 }
9319
Chalard Jeane6c95272022-01-25 21:04:21 +09009320 private static UidRangeParcel[] intsToUidRangeStableParcels(
9321 final @NonNull ArraySet<Integer> uids) {
9322 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9323 int index = 0;
9324 for (int uid : uids) {
9325 stableRanges[index] = new UidRangeParcel(uid, uid);
9326 index++;
9327 }
9328 return stableRanges;
9329 }
9330
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009331 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9332 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9333 for (int i = 0; i < ranges.length; i++) {
9334 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9335 }
9336 return stableRanges;
9337 }
9338
Motomu Utsumi93a22182023-03-16 17:04:21 +09009339 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009340 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009341 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9342 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009343 if (mDeps.isAtLeastU()) {
9344 final Set<Integer> exemptUidSet = new ArraySet<>();
9345 for (final int uid: exemptUids) {
9346 exemptUidSet.add(uid);
9347 }
9348 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9349 } else {
9350 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9351 }
Ken Chen5e65a852020-12-24 12:59:10 +08009352 } catch (Exception e) {
9353 loge("Exception in socket destroy: ", e);
9354 }
9355 }
9356 }
9357
paulhuaa0743d2021-05-26 21:56:03 +08009358 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009359 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009360 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9361 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9362 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009363 exemptUids[0] = VPN_UID;
9364 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009365 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9366
Motomu Utsumi6345e462023-03-13 13:24:50 +09009367 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009368 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009369 try {
9370 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009371 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009372 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009373 } else {
paulhu0e79d952021-06-09 16:11:35 +08009374 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009375 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009376 }
9377 } catch (Exception e) {
9378 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9379 " on netId " + nai.network.netId + ". " + e);
9380 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009381 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009382 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009383 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009384
lucaslin53e8a262021-06-08 01:43:59 +08009385 private boolean isProxySetOnAnyDefaultNetwork() {
9386 ensureRunningOnConnectivityServiceThread();
9387 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9388 final NetworkAgentInfo nai = nri.getSatisfier();
9389 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9390 return true;
9391 }
9392 }
9393 return false;
9394 }
9395
9396 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9397 NetworkCapabilities newNc) {
9398 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9399 // the proxy might be changed since the default network satisfied by the apps might also
9400 // changed.
9401 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9402 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009403 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9404 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009405 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009406 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9407 mProxyTracker.sendProxyBroadcast();
9408 }
9409 }
9410
Chalard Jeane6c95272022-01-25 21:04:21 +09009411 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9412 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009413 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9414 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009415 if (null == prevRanges) prevRanges = new ArraySet<>();
9416 if (null == newRanges) newRanges = new ArraySet<>();
9417 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9418
9419 prevRanges.removeAll(newRanges);
9420 newRanges.removeAll(prevRangesCopy);
9421
9422 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009423 // When updating the VPN uid routing rules, add the new range first then remove the old
9424 // range. If old range were removed first, there would be a window between the old
9425 // range being removed and the new range being added, during which UIDs contained
9426 // in both ranges are not subject to any VPN routing rules. Adding new range before
9427 // removing old range works because, unlike the filtering rules below, it's possible to
9428 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009429 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9430 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9431 // [1-5] & [1-2],[4-5] == [3]
9432 // Then we can do:
9433 // maybeCloseSockets([3])
9434 // mNetd.networkAddUidRanges([1-2],[4-5])
9435 // mNetd.networkRemoveUidRanges([1-5])
9436 // maybeCloseSockets([3])
9437 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9438 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009439 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009440 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009441 }
9442 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009443 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009444 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009445 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9446 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009447 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9448 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009449 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009450 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009451 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9452 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9453 // were added first and then newRanges got removed later, there would be only one uid
9454 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9455 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9456 // Note that this is in contrast with the (more robust) update of VPN routing rules
9457 // above, where the addition of new ranges happens before the removal of old ranges.
9458 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9459 // to be removed will never overlap with the new range to be added.
9460 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009461 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9462 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009463 }
9464 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009465 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009466 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009467 } catch (Exception e) {
9468 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009469 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009470 }
9471 }
9472
Chalard Jeande665262022-02-25 16:12:12 +09009473 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009474 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9475 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009476 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9477 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009478 if (prevEmpty && newEmpty) return;
9479
9480 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009481 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009482 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009483 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009484
9485 if (prevUids.equals(newUids)) return;
9486
9487 // This implementation is very simple and vastly faster for sets of Integers than
9488 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9489 // a key computed from the value and has storage for that.
9490 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9491 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9492 toRemove.removeAll(newUids);
9493 toAdd.removeAll(prevUids);
9494
9495 try {
9496 if (!toAdd.isEmpty()) {
9497 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9498 nai.network.netId,
9499 intsToUidRangeStableParcels(toAdd),
9500 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9501 }
9502 if (!toRemove.isEmpty()) {
9503 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9504 nai.network.netId,
9505 intsToUidRangeStableParcels(toRemove),
9506 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9507 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009508 } catch (ServiceSpecificException e) {
9509 // Has the interface disappeared since the network was built ?
9510 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009511 } catch (RemoteException e) {
9512 // Netd died. This usually causes a runtime restart anyway.
9513 }
9514 }
9515
Junyu Lai2ed7d412022-10-07 16:52:21 +08009516 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9517 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009518 ensureRunningOnConnectivityServiceThread();
9519
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009520 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009521 // Ignore updates for disconnected networks
9522 return;
9523 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009524 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009525 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009526 + "; created=" + nai.getCreatedTime()
9527 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009528 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009529 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9530 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009531 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009532 }
9533
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009534 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9535 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009536 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009537 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009538 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009539 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9540 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9541 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009542 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9543 // need to be sent as a separate extra.
9544 final NetworkRequest req = nri.isMultilayerRequest()
9545 ? nri.getActiveRequest()
9546 // Non-multilayer listen requests do not have an active request
9547 : nri.mRequests.get(0);
9548 if (req == null) {
9549 Log.wtf(TAG, "No request in NRI " + nri);
9550 }
9551 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009552 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009553 sendIntent(nri.mPendingIntent, intent);
9554 }
9555 // else not handled
9556 }
9557
Michael Groover73f69482023-01-27 11:01:25 -06009558 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9559 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009560 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9561 mPendingIntentWakeLock.acquire();
9562 try {
9563 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009564 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009565 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009566 // Explicitly disallow the receiver from starting activities, to prevent apps from
9567 // utilizing the PendingIntent as a backdoor to do this.
9568 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9569 }
9570 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9571 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009572 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009573 } catch (PendingIntent.CanceledException e) {
9574 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9575 mPendingIntentWakeLock.release();
9576 releasePendingNetworkRequest(pendingIntent);
9577 }
9578 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9579 }
9580
9581 @Override
9582 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9583 String resultData, Bundle resultExtras) {
9584 if (DBG) log("Finished sending " + pendingIntent);
9585 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009586 // Release with a delay so the receiving client has an opportunity to put in its
9587 // own request.
9588 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009589 }
9590
Chalard Jean22350c92023-10-07 19:21:45 +09009591 @Nullable
9592 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9593 if (!nai.isLocalNetwork()) return null;
9594 final Network upstream;
9595 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9596 if (null == selector) {
9597 upstream = null;
9598 } else {
9599 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9600 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9601 upstream = (null == satisfier) ? null : satisfier.network;
9602 }
9603 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9604 }
9605
Chalard Jean46bfbf02022-02-02 00:56:25 +09009606 // networkAgent is only allowed to be null if notificationType is
9607 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9608 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009609 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009610 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009611 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009612 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009613 // Default request has no msgr. Also prevents callbacks from being invoked for
9614 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9615 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9616 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009617 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009618 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009619 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009620 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009621 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009622 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009623 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009624 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9625 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009626 }
Roshan Pius951c0032020-12-22 15:10:42 -08009627 final boolean includeLocationSensitiveInfo =
9628 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009629 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009630 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009631 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009632 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009633 networkCapabilitiesRestrictedForCallerPermissions(
9634 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9635 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009636 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009637 nri.mCallingAttributionTag);
9638 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009639 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9640 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009641 // The local network info is often null, so can't use the static putParcelable
9642 // method here.
9643 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9644 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009645 // For this notification, arg1 contains the blocked status.
9646 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009647 break;
9648 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009649 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009650 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009651 break;
9652 }
9653 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009654 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009655 final NetworkCapabilities netCap =
9656 networkCapabilitiesRestrictedForCallerPermissions(
9657 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9658 putParcelable(
9659 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009660 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009661 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009662 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009663 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009664 break;
9665 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009666 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009667 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9668 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009669 break;
9670 }
junyulaif2c67e42018-08-07 19:50:45 +08009671 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009672 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009673 msg.arg1 = arg1;
9674 break;
9675 }
Chalard Jean22350c92023-10-07 19:21:45 +09009676 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9677 if (!networkAgent.isLocalNetwork()) {
9678 Log.wtf(TAG, "Callback for local info for a non-local network");
9679 return;
9680 }
9681 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9682 break;
9683 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009684 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009685 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009686 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009687 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009688 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009689 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009690 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009691 }
James Mattis45d81842021-01-10 14:24:24 -08009692 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009693 } catch (RemoteException e) {
9694 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009695 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009696 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009697 }
9698
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009699 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9700 bundle.putParcelable(t.getClass().getSimpleName(), t);
9701 }
9702
Chalard Jean0702f982021-09-16 21:50:07 +09009703 /**
9704 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9705 *
9706 * When a request should be assigned to a new network, it is normally lingered to give
9707 * time for apps to gracefully migrate their connections. When both networks are on the same
9708 * radio, but that radio can't do time-sharing efficiently, this may end up being
9709 * counter-productive because any traffic on the old network may drastically reduce the
9710 * performance of the new network.
9711 * The stack supports a configuration to let modem vendors state that their radio can't
9712 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9713 * from one cell network to another can't be done gracefully.
9714 *
9715 * @param oldNai the old network serving the request
9716 * @param newNai the new network serving the request
9717 * @return whether the switch can be graceful
9718 */
9719 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9720 @NonNull final NetworkAgentInfo newSatisfier) {
9721 if (mCellularRadioTimesharingCapable) return true;
9722 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9723 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9724 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9725 }
9726
Paul Jensenaf94b982014-09-30 15:37:41 -04009727 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009728 if (nai.numRequestNetworkRequests() != 0) {
9729 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9730 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009731 // Ignore listening and track default requests.
9732 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009733 loge("Dead network still had at least " + nr);
9734 break;
9735 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009736 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009737 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009738 }
9739
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009740 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9741 if (oldNetwork == null) {
9742 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9743 return;
9744 }
Chalard Jean49707572019-12-10 21:07:02 +09009745 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009746
9747 // If we get here it means that the last linger timeout for this network expired. So there
9748 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009749 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009750
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009751 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009752 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009753 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009754 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009755 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009756 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009757 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009758 }
9759
James Mattise3ef1912020-12-20 11:09:58 -08009760 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9761 boolean isDefaultChanged = false;
9762 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9763 final NetworkReassignment.RequestReassignment reassignment =
9764 changes.getReassignment(defaultRequestInfo);
9765 if (null == reassignment) {
9766 continue;
9767 }
9768 // reassignment only contains those instances where the satisfying network changed.
9769 isDefaultChanged = true;
9770 // Notify system services of the new default.
9771 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9772 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009773
James Mattise3ef1912020-12-20 11:09:58 -08009774 if (isDefaultChanged) {
9775 // Hold a wakelock for a short time to help apps in migrating to a new default.
9776 scheduleReleaseNetworkTransitionWakelock();
9777 }
9778 }
9779
Aaron Huang9fe47be2021-06-08 13:11:45 +08009780 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9781 if (null == oldDefaultNetwork) return;
9782 // The network stopped being the default. If it was using a PAC proxy, then the
9783 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9784 // to the local proxy server, which would forward them over the newly default network.
9785 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9786 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9787 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9788 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9789 }
9790
James Mattise3ef1912020-12-20 11:09:58 -08009791 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9792 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9793 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9794 if (DBG) {
9795 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9796 }
Chalard Jean8e382112019-12-03 20:45:30 +09009797
James Mattisd31bdfa2020-12-23 16:37:26 -08009798 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9799 if (newDefaultNetwork != null) {
9800 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009801 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009802
James Mattisd31bdfa2020-12-23 16:37:26 -08009803 // Set an app level managed default and return since further processing only applies to the
9804 // default network.
9805 if (mDefaultRequest != nri) {
9806 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9807 return;
9808 }
9809
9810 makeDefaultNetwork(newDefaultNetwork);
9811
James Mattise3ef1912020-12-20 11:09:58 -08009812 if (oldDefaultNetwork != null) {
9813 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9814 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009815 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009816 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009817 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009818 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009819 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009820 updateTcpBufferSizes(null != newDefaultNetwork
9821 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009822 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009823 }
9824
James Mattisd31bdfa2020-12-23 16:37:26 -08009825 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9826 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9827 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9828 try {
9829 if (VDBG) {
9830 log("Setting default network for " + nri
9831 + " using UIDs " + nri.getUids()
9832 + " with old network " + (oldDefaultNetwork != null
9833 ? oldDefaultNetwork.network().getNetId() : "null")
9834 + " and new network " + (newDefaultNetwork != null
9835 ? newDefaultNetwork.network().getNetId() : "null"));
9836 }
9837 if (nri.getUids().isEmpty()) {
9838 throw new IllegalStateException("makeDefaultForApps called without specifying"
9839 + " any applications to set as the default." + nri);
9840 }
9841 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009842 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009843 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009844 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009845 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009846 }
9847 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009848 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009849 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009850 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009851 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009852 }
9853 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009854 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009855 }
9856 }
9857
Junyu Lai35665cc2022-12-19 17:37:48 +08009858 /**
9859 * Collect restricted uid ranges for the given network and UserHandle, these uids
9860 * are not restricted for matched enterprise networks but being restricted for non-matched
9861 * enterprise networks and non-enterprise networks.
9862 */
9863 @NonNull
9864 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9865 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9866 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9867 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9868 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9869
9870 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9871 // The NC is built from a `ProfileNetworkPreference` which has only one
9872 // enterprise ID, so it's guaranteed to have exactly one.
9873 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9874 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9875 continue;
9876 }
9877 }
9878
9879 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9880 pref.capabilities.getUidRanges())) {
9881 throw new IllegalArgumentException(
9882 "Overlapping uid range in preference: " + pref);
9883 }
9884 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9885 }
9886 return restrictedUidRanges;
9887 }
9888
9889 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009890 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009891 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009892
Junyu Lai35665cc2022-12-19 17:37:48 +08009893 ensureRunningOnConnectivityServiceThread();
9894 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9895 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9896 .getUserHandles(true /* excludeDying */);
9897 if (users.isEmpty()) {
9898 throw new IllegalStateException("No user is available");
9899 }
9900
9901 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9902 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9903 for (final UserHandle user : users) {
9904 final ArraySet<UidRange> restrictedUidRanges =
9905 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9906 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9907 UidRange.createForUser(user), restrictedUidRanges));
9908 }
9909
9910 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9911 configs.add(new NativeUidRangeConfig(
9912 nai.network.netId, rangesParcel, 0 /* subPriority */));
9913 }
9914
9915 // The netd API replaces the previous configs with the current configs.
9916 // Thus, for network disconnection or preference removal, no need to
9917 // unset previous config. Instead, collecting all currently needed
9918 // configs and issue to netd.
9919 try {
9920 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9921 } catch (ServiceSpecificException e) {
9922 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009923 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009924 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009925 // Netd died. This will cause a runtime restart anyway.
9926 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009927 }
9928 }
9929
James Mattisd31bdfa2020-12-23 16:37:26 -08009930 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9931 try {
9932 if (null != newDefaultNetwork) {
9933 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9934 } else {
9935 mNetd.networkClearDefault();
9936 }
9937 } catch (RemoteException | ServiceSpecificException e) {
9938 loge("Exception setting default network :" + e);
9939 }
9940 }
9941
Chalard Jean05cbe972019-12-09 11:50:38 +09009942 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009943 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009944 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009945 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009946 processNewlySatisfiedListenRequests(nai);
9947 }
9948
9949 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009950 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9951 if (nri.isMultilayerRequest()) {
9952 continue;
9953 }
9954 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009955 if (!nr.isListen()) continue;
9956 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009957 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009958 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9959 }
9960 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009961 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009962
Chalard Jeancd397a22019-11-22 22:33:33 +09009963 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009964 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9965 if (nri.isMultilayerRequest()) {
9966 continue;
9967 }
9968 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009969 if (!nr.isListen()) continue;
9970 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9971 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009972 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009973 }
9974 }
9975 }
9976
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009977 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009978 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009979 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009980 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009981 @Nullable public final NetworkRequest mOldNetworkRequest;
9982 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009983 @Nullable public final NetworkAgentInfo mOldNetwork;
9984 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009985 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009986 @Nullable final NetworkRequest oldNetworkRequest,
9987 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009988 @Nullable final NetworkAgentInfo oldNetwork,
9989 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009990 mNetworkRequestInfo = networkRequestInfo;
9991 mOldNetworkRequest = oldNetworkRequest;
9992 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009993 mOldNetwork = oldNetwork;
9994 mNewNetwork = newNetwork;
9995 }
Chalard Jean49707572019-12-10 21:07:02 +09009996
9997 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009998 final NetworkRequest requestToShow = null != mNewNetworkRequest
9999 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
10000 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -080010001 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
10002 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +090010003 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010004 }
10005
Chalard Jean46a62372019-12-10 21:25:24 +090010006 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010007
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010008 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +090010009 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010010 }
10011
10012 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +090010013 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +090010014 // The code is never supposed to add two reassignments of the same request. Make
10015 // sure this stays true, but without imposing this expensive check on all
10016 // reassignments on all user devices.
10017 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -080010018 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +090010019 throw new IllegalStateException("Trying to reassign ["
10020 + reassignment + "] but already have ["
10021 + existing + "]");
10022 }
10023 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +090010024 }
Chalard Jean46a62372019-12-10 21:25:24 +090010025 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010026 }
10027
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010028 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +090010029 // the passed request.
10030 @Nullable
10031 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010032 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010033 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010034 }
10035 return null;
10036 }
Chalard Jean49707572019-12-10 21:07:02 +090010037
10038 public String toString() {
10039 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
10040 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +090010041 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010042 for (final RequestReassignment rr : getRequestReassignments()) {
10043 sj.add(rr.toString());
10044 }
10045 return sj.toString();
10046 }
10047
10048 public String debugString() {
10049 final StringBuilder sb = new StringBuilder();
10050 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +090010051 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010052 for (final RequestReassignment rr : getRequestReassignments()) {
10053 sb.append("\n ").append(rr);
10054 }
10055 return sb.append("\n").toString();
10056 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010057 }
10058
Chalard Jean24344d72019-12-04 13:32:31 +090010059 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010060 @Nullable final NetworkRequest previousRequest,
10061 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +090010062 @Nullable final NetworkAgentInfo previousSatisfier,
10063 @Nullable final NetworkAgentInfo newSatisfier,
10064 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -080010065 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +090010066 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +090010067 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010068 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010069 log(" accepting network in place of " + previousSatisfier.toShortString()
10070 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010071 }
James Mattisa076c532020-12-02 14:12:41 -080010072 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010073 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +090010074 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +090010075 // If this network switch can't be supported gracefully, the request is not
10076 // lingered. This allows letting go of the network sooner to reclaim some
10077 // performance on the new network, since the radio can't do both at the same
10078 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010079 //
10080 // Also don't linger the request if the old network has been destroyed.
10081 // A destroyed network does not provide actual network connectivity, so
10082 // lingering it is not useful. In particular this ensures that a destroyed
10083 // network is outscored by its replacement,
10084 // then it is torn down immediately instead of being lingered, and any apps that
10085 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +090010086 previousSatisfier.lingerRequest(previousRequest.requestId, now);
10087 }
Chalard Jean24344d72019-12-04 13:32:31 +090010088 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010089 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010090 }
junyulai0ac374f2020-12-14 18:41:52 +080010091
10092 // To prevent constantly CPU wake up for nascent timer, if a network comes up
10093 // and immediately satisfies a request then remove the timer. This will happen for
10094 // all networks except in the case of an underlying network for a VCN.
10095 if (newSatisfier.isNascent()) {
10096 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +080010097 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010098 }
10099
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010100 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -080010101 newSatisfier.unlingerRequest(newRequest.requestId);
10102 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +080010103 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -080010104 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010105 }
Chalard Jeana8ac2302021-03-01 22:16:08 +090010106 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010107 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010108 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -080010109 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010110 }
James Mattisa076c532020-12-02 14:12:41 -080010111 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010112 }
James Mattisa076c532020-12-02 14:12:41 -080010113 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010114 }
10115
James Mattisa076c532020-12-02 14:12:41 -080010116 /**
10117 * This function is triggered when something can affect what network should satisfy what
10118 * request, and it computes the network reassignment from the passed collection of requests to
10119 * network match to the one that the system should now have. That data is encoded in an
10120 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
10121 * satisfier.
10122 *
10123 * After the reassignment is computed, it is applied to the state objects.
10124 *
10125 * @param networkRequests the nri objects to evaluate for possible network reassignment
10126 * @return NetworkReassignment listing of proposed network assignment changes
10127 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010128 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080010129 private NetworkReassignment computeNetworkReassignment(
10130 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010131 final NetworkReassignment changes = new NetworkReassignment();
10132
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010133 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010134 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010135 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010136 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010137 }
Chalard Jean857a1712019-12-10 21:08:07 +090010138
James Mattisa076c532020-12-02 14:12:41 -080010139 for (final NetworkRequestInfo nri : networkRequests) {
10140 // Non-multilayer listen requests can be ignored.
10141 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10142 continue;
10143 }
10144 NetworkAgentInfo bestNetwork = null;
10145 NetworkRequest bestRequest = null;
10146 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010147 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010148 // Stop evaluating as the highest possible priority request is satisfied.
10149 if (null != bestNetwork) {
10150 bestRequest = req;
10151 break;
10152 }
10153 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010154 if (null == bestNetwork && isDefaultBlocked(nri)) {
10155 // Remove default networking if disallowed for managed default requests.
10156 bestNetwork = mNoServiceNetwork;
10157 }
10158 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010159 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010160 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010161 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010162 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010163 }
10164 return changes;
10165 }
10166
James Mattisa076c532020-12-02 14:12:41 -080010167 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10168 return new HashSet<>(mNetworkRequests.values());
10169 }
10170
Paul Jensenc88b39b2015-06-16 14:27:36 -040010171 /**
James Mattisa076c532020-12-02 14:12:41 -080010172 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010173 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010174 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010175 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010176 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10177 }
10178
10179 /**
10180 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10181 * being disconnected.
10182 */
10183 private void rematchNetworksAndRequests(
10184 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10185 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010186 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010187 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010188 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010189 final long computed = SystemClock.elapsedRealtime();
10190 applyNetworkReassignment(changes, start);
10191 final long applied = SystemClock.elapsedRealtime();
10192 issueNetworkNeeds();
10193 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010194 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010195 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10196 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010197 log(changes.debugString());
10198 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010199 // Shorter form, only one line of log
10200 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10201 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010202 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010203 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010204
Chalard Jean1e4c2182023-10-06 18:45:53 +090010205 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10206 @Nullable final NetworkAgentInfo nai2) {
10207 if (null == nai1) return null == nai2;
10208 if (null == nai2) return false;
10209 return nai1.linkProperties.getInterfaceName()
10210 .equals(nai2.linkProperties.getInterfaceName());
10211 }
10212
Chalard Jeand7f762d2019-12-10 19:01:29 +090010213 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010214 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010215 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010216
10217 // Since most of the time there are only 0 or 1 background networks, it would probably
10218 // be more efficient to just use an ArrayList here. TODO : measure performance
10219 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10220 for (final NetworkAgentInfo nai : nais) {
10221 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10222 }
10223
Chalard Jeand7f762d2019-12-10 19:01:29 +090010224 // First, update the lists of satisfied requests in the network agents. This is necessary
10225 // because some code later depends on this state to be correct, most prominently computing
10226 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010227 for (final NetworkReassignment.RequestReassignment event :
10228 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010229 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10230 event.mOldNetworkRequest, event.mNewNetworkRequest,
10231 event.mOldNetwork, event.mNewNetwork,
10232 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010233 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010234
James Mattise3ef1912020-12-20 11:09:58 -080010235 // Process default network changes if applicable.
10236 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010237
Chalard Jean68eab722023-11-16 17:00:04 +090010238 // Update forwarding rules for the upstreams of local networks. Do this before sending
10239 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10240 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10241 // onAvailable so clients know what network the change is about. Store such changes in
10242 // an array that's only allocated if necessary (because it's almost never necessary).
10243 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10244 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10245 if (!nai.isLocalNetwork()) continue;
10246 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10247 if (null == nr) continue; // No upstream for this local network
10248 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10249 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10250 if (null == change) continue; // No change in upstreams for this network
10251 final String fromIface = nai.linkProperties.getInterfaceName();
10252 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10253 || change.mOldNetwork.isDestroyed()) {
10254 // There can be a change with the same interface name if the new network is the
10255 // replacement for the old network that was unregisteredAfterReplacement.
10256 try {
10257 if (null != change.mOldNetwork) {
10258 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10259 change.mOldNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010260 disableMulticastRouting(fromIface,
10261 change.mOldNetwork.linkProperties.getInterfaceName());
Chalard Jean68eab722023-11-16 17:00:04 +090010262 }
10263 // If the new upstream is already destroyed, there is no point in setting up
10264 // a forward (in fact, it might forward to the interface for some new network !)
10265 // Later when the upstream disconnects CS will try to remove the forward, which
10266 // is ignored with a benign log by RoutingCoordinatorService.
10267 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10268 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10269 change.mNewNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010270 applyMulticastRoutingConfig(fromIface,
10271 change.mNewNetwork.linkProperties.getInterfaceName(),
10272 nai.localNetworkConfig);
Chalard Jean68eab722023-11-16 17:00:04 +090010273 }
10274 } catch (final RemoteException e) {
10275 loge("Can't update forwarding rules", e);
10276 }
10277 }
10278 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10279 localInfoChangedAgents.add(nai);
10280 }
10281
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010282 // Notify requested networks are available after the default net is switched, but
10283 // before LegacyTypeTracker sends legacy broadcasts
10284 for (final NetworkReassignment.RequestReassignment event :
10285 changes.getRequestReassignments()) {
10286 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010287 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010288 } else {
James Mattisa076c532020-12-02 14:12:41 -080010289 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010290 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010291 }
10292 }
10293
junyulai0ac374f2020-12-14 18:41:52 +080010294 // Update the inactivity state before processing listen callbacks, because the background
10295 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010296 // just yet though, because they have to be sent after the listens are processed to keep
10297 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010298 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010299 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010300 // Rematching may have altered the inactivity state of some networks, so update all
10301 // inactivity timers. updateInactivityState reads the state from the network agent
10302 // and does nothing if the state has not changed : the source of truth is controlled
10303 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10304 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010305 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010306 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010307 }
10308 }
10309
Chalard Jeanb10ab412019-12-11 14:12:30 +090010310 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010311 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010312 // Process listen requests and update capabilities if the background state has
10313 // changed for this network. For consistency with previous behavior, send onLost
10314 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010315 processNewlyLostListenRequests(nai);
10316 if (oldBackground != nai.isBackgroundNetwork()) {
10317 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010318 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010319 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010320 }
10321
junyulai0ac374f2020-12-14 18:41:52 +080010322 for (final NetworkAgentInfo nai : inactiveNetworks) {
10323 // For nascent networks, if connecting with no foreground request, skip broadcasting
10324 // LOSING for backward compatibility. This is typical when mobile data connected while
10325 // wifi connected with mobile data always-on enabled.
10326 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010327 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010328 }
10329
Chalard Jean68eab722023-11-16 17:00:04 +090010330 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10331 if (null != localInfoChangedAgents) {
10332 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10333 notifyNetworkCallbacks(nai,
10334 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010335 }
10336 }
10337
James Mattise3ef1912020-12-20 11:09:58 -080010338 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010339
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010340 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010341 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010342 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010343 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010344 // This network has active linger timers and no requests, but is not
10345 // lingering. Linger it.
10346 //
10347 // One way (the only way?) this can happen if this network is unvalidated
10348 // and became unneeded due to another network improving its score to the
10349 // point where this network will no longer be able to satisfy any requests
10350 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010351 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010352 notifyNetworkLosing(nai, now);
10353 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010354 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010355 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010356 teardownUnneededNetwork(nai);
10357 }
10358 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010359 }
10360 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010361
Chalard Jean62edfd82019-12-02 18:39:29 +090010362 /**
10363 * Apply a change in background state resulting from rematching networks with requests.
10364 *
10365 * During rematch, a network may change background states by starting to satisfy or stopping
10366 * to satisfy a foreground request. Listens don't count for this. When a network changes
10367 * background states, its capabilities need to be updated and callbacks fired for the
10368 * capability change.
10369 *
10370 * @param nai The network that changed background states
10371 */
10372 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10373 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10374 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10375 updateNetworkPermissions(nai, newNc);
10376 nai.getAndSetNetworkCapabilities(newNc);
10377 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10378 }
10379
Chalard Jeanf0344532019-11-19 19:23:38 +090010380 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010381 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010382 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010383 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10384 changes.getReassignment(mDefaultRequest);
10385 final NetworkAgentInfo oldDefaultNetwork =
10386 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10387 final NetworkAgentInfo newDefaultNetwork =
10388 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010389
Chalard Jean5b409c72021-02-04 13:12:59 +090010390 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010391 // Maintain the illusion : since the legacy API only understands one network at a time,
10392 // if the default network changed, apps should see a disconnected broadcast for the
10393 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010394 if (oldDefaultNetwork != null) {
10395 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10396 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010397 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010398 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010399 // The new default network can be newly null if and only if the old default
10400 // network doesn't satisfy the default request any more because it lost a
10401 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010402 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010403 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010404 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010405 }
10406 }
10407
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010408 // Now that all the callbacks have been sent, send the legacy network broadcasts
10409 // as needed. This is necessary so that legacy requests correctly bind dns
10410 // requests to this network. The legacy users are listening for this broadcast
10411 // and will generally do a dns request so they can ensureRouteToHost and if
10412 // they do that before the callbacks happen they'll use the default network.
10413 //
10414 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10415 // callbacks, but if apps can receive the broadcast before the callback, they still might
10416 // have an inconsistent view of networking.
10417 //
10418 // This *does* introduce a race where if the user uses the new api
10419 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10420 // they may get old info. Reverse this after the old startUsing api is removed.
10421 // This is on top of the multiple intent sequencing referenced in the todo above.
10422 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010423 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010424 addNetworkToLegacyTypeTracker(nai);
10425 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010426 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010427 }
10428
Chalard Jean0354d8c2021-01-12 10:58:56 +090010429 private void issueNetworkNeeds() {
10430 ensureRunningOnConnectivityServiceThread();
10431 for (final NetworkOfferInfo noi : mNetworkOffers) {
10432 issueNetworkNeeds(noi);
10433 }
10434 }
10435
10436 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10437 ensureRunningOnConnectivityServiceThread();
10438 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10439 informOffer(nri, noi.offer, mNetworkRanker);
10440 }
10441 }
10442
10443 /**
10444 * Inform a NetworkOffer about any new situation of a request.
10445 *
10446 * This function handles updates to offers. A number of events may happen that require
10447 * updating the registrant for this offer about the situation :
10448 * • The offer itself was updated. This may lead the offer to no longer being able
10449 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10450 * or conversely being strengthened enough to beat the satisfier (and therefore
10451 * start being needed)
10452 * • The network satisfying a request changed (including cases where the request
10453 * starts or stops being satisfied). The new network may be a stronger or weaker
10454 * match than the old one, possibly affecting whether the offer is needed.
10455 * • The network satisfying a request updated their score. This may lead the offer
10456 * to no longer be able to beat it if the current satisfier got better, or
10457 * conversely start being a good choice if the current satisfier got weaker.
10458 *
10459 * @param nri The request
10460 * @param offer The offer. This may be an updated offer.
10461 */
10462 private static void informOffer(@NonNull NetworkRequestInfo nri,
10463 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10464 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10465 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010466
10467 // Multi-layer requests have a currently active request, the one being satisfied.
10468 // Since the system will try to bring up a better network than is currently satisfying
10469 // the request, NetworkProviders need to be told the offers matching the requests *above*
10470 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10471 // not needed, and the offer is needed for the active request iff the offer can beat
10472 // the satisfier.
10473 // For non-multilayer requests, the logic above gracefully degenerates to only the
10474 // last case.
10475 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10476 // providers that the offer is needed for this request, until the active request is found.
10477 // In a second phase, deal with the currently active request. In a third phase, inform
10478 // the providers that offer is unneeded for the remaining requests.
10479
10480 // First phase : inform providers of all requests above the active request.
10481 int i;
10482 for (i = 0; nri.mRequests.size() > i; ++i) {
10483 final NetworkRequest request = nri.mRequests.get(i);
10484 if (activeRequest == request) break; // Found the active request : go to phase 2
10485 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10486 // Since this request is higher-priority than the one currently satisfied, if the
10487 // offer can satisfy it, the provider should try and bring up the network for sure ;
10488 // no need to even ask the ranker – an offer that can satisfy is always better than
10489 // no network. Hence tell the provider so unless it already knew.
10490 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10491 offer.onNetworkNeeded(request);
10492 }
10493 }
10494
10495 // Second phase : deal with the active request (if any)
10496 if (null != activeRequest && activeRequest.isRequest()) {
10497 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010498 // If an offer can satisfy the request, it is considered needed if it is currently
10499 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010500 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010501 && satisfier.factorySerialNumber == offer.providerId
10502 && activeRequest.canBeSatisfiedBy(offer.caps);
10503 final boolean newNeeded = currentlyServing
10504 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010505 if (newNeeded != oldNeeded) {
10506 if (newNeeded) {
10507 offer.onNetworkNeeded(activeRequest);
10508 } else {
10509 // The offer used to be able to beat the satisfier. Now it can't.
10510 offer.onNetworkUnneeded(activeRequest);
10511 }
10512 }
10513 }
10514
10515 // Third phase : inform the providers that the offer isn't needed for any request
10516 // below the active one.
10517 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10518 final NetworkRequest request = nri.mRequests.get(i);
10519 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10520 // Since this request is lower-priority than the one currently satisfied, if the
10521 // offer can satisfy it, the provider should not try and bring up the network.
10522 // Hence tell the provider so unless it already knew.
10523 if (offer.neededFor(request)) {
10524 offer.onNetworkUnneeded(request);
10525 }
10526 }
10527 }
10528
Chalard Jean61c79252019-11-07 23:07:32 +090010529 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10530 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10531 NetworkRequest nr = nai.requestAt(i);
10532 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10533 // legacy type tracker filters out repeat adds
10534 mLegacyTypeTracker.add(nr.legacyType, nai);
10535 }
10536 }
10537
10538 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010539 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010540 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10541 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10542 if (nai.isVPN()) {
10543 mLegacyTypeTracker.add(TYPE_VPN, nai);
10544 }
10545 }
10546
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010547 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010548 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010549 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010550 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010551 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010552 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010553
Chalard Jean254bd162022-08-25 13:04:51 +090010554 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010555 // Don't repeat publish.
10556 if (newInetCondition == mDefaultInetConditionPublished) return;
10557
10558 mDefaultInetConditionPublished = newInetCondition;
10559 sendInetConditionBroadcast(nai.networkInfo);
10560 }
10561
Chalard Jeand61375d2020-01-14 22:46:36 +090010562 @NonNull
10563 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10564 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010565 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010566 final boolean suspended =
10567 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10568 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10569 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10570 // state. This is because the network could have been suspended before connecting,
10571 // or it could be disconnecting while being suspended, and in both these cases
10572 // the state should not be overridden. Note that the only detailed state that
10573 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10574 // worry about multiple different substates of CONNECTED.
10575 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10576 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010577 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10578 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10579 // network agent is created, then goes to suspended, then goes out of suspended without
10580 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010581 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010582 ? NetworkInfo.DetailedState.CONNECTED
10583 : NetworkInfo.DetailedState.CONNECTING,
10584 info.getReason(),
10585 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010586 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010587 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010588 return newInfo;
10589 }
10590
10591 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10592 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10593
Erik Kline99f301b2017-02-15 19:59:17 +090010594 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010595 NetworkInfo oldInfo = null;
10596 synchronized (networkAgent) {
10597 oldInfo = networkAgent.networkInfo;
10598 networkAgent.networkInfo = newInfo;
10599 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010600
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010601 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010602 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10603 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010604 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010605
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010606 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010607 // A network that has just connected has zero requests and is thus a foreground network.
10608 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10609
Luke Huangfdd11f82019-04-09 18:41:49 +080010610 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010611
10612 networkAgent.setCreated();
10613
10614 // If the network is created immediately on register, then apply the LinkProperties now.
10615 // Otherwise, this is done further down when the network goes into connected state.
10616 // Applying the LinkProperties means that the network is ready to carry traffic -
10617 // interfaces and routing rules have been added, DNS servers programmed, etc.
10618 // For VPNs, this must be done before the capabilities are updated, because as soon as
10619 // that happens, UIDs are routed to the network.
10620 if (shouldCreateNetworksImmediately()) {
10621 applyInitialLinkProperties(networkAgent);
10622 }
10623
10624 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10625 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010626 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010627 // Initialize the network's capabilities to their starting values according to the
10628 // underlying networks. This ensures that the capabilities are correct before
10629 // anything happens to the network.
10630 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010631 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010632 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010633 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010634 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010635 }
10636
Chalard Jean254bd162022-08-25 13:04:51 +090010637 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10638 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010639
lucaslin45e639b2019-04-03 17:09:28 +080010640 // NetworkCapabilities need to be set before sending the private DNS config to
10641 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010642 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10643
Erik Kline9a62f012018-03-21 07:18:33 -070010644 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010645 if (!shouldCreateNetworksImmediately()) {
10646 applyInitialLinkProperties(networkAgent);
10647 } else {
10648 // The network was created when the agent registered, and the LinkProperties are
10649 // already up-to-date. However, updateLinkProperties also makes some changes only
10650 // when the network connects. Apply those changes here. On T and below these are
10651 // handled by the applyInitialLinkProperties call just above.
10652 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10653 // If something depends on both LinkProperties and connected state, it should be in
10654 // this method as well.
10655 networkAgent.clatd.update();
10656 updateProxy(networkAgent.linkProperties, null);
10657 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010658
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010659 // If a rate limit has been configured and is applicable to this network (network
10660 // provides internet connectivity), apply it. The tc police filter cannot be attached
10661 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010662 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010663 // Note: in case of a system server crash, the NetworkController constructor in netd
10664 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10665 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10666 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10667 mIngressRateLimit);
10668 }
10669
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010670 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10671 // command must be sent after updating LinkProperties to maximize chances of
10672 // NetworkMonitor seeing the correct LinkProperties when starting.
10673 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010674 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010675 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010676 }
Chalard Jeand4900722022-02-06 12:25:38 +090010677 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10678 params.networkAgentConfig = networkAgent.networkAgentConfig;
10679 params.networkCapabilities = networkAgent.networkCapabilities;
10680 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10681 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010682 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10683 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10684 // call that would cause a Log.wtf to be emitted from the system_server process, and
10685 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10686 // process to check the interface version, just use an SDK check. NetworkStack will
10687 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010688 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010689 networkAgent.networkMonitor().notifyNetworkConnected(params);
10690 } else {
10691 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10692 params.networkCapabilities);
10693 }
Chalard Jean0f141332023-06-05 19:26:17 +090010694 final long evaluationDelay;
10695 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10696 // If the network is anything other than pure wifi, use the default timeout.
10697 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10698 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10699 // If the network is explicitly selected, use the default timeout because it's
10700 // shorter and the user is likely staring at the screen expecting it to validate
10701 // right away.
10702 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10703 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10704 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10705 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10706 } else {
10707 // It's wifi, automatically connected, and bad wifi is preferred : use the
10708 // longer timeout to avoid the device switching to captive portals with bad
10709 // signal or very slow response.
10710 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10711 }
10712 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010713
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010714 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10715 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10716 // capabilities, so it only needs to be done once on initial connect, not every time the
10717 // network's capabilities change. Note that we do this before rematching the network,
10718 // so we could decide to tear it down immediately afterwards. That's fine though - on
10719 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10720 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010721 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010722
junyulai0ac374f2020-12-14 18:41:52 +080010723 // Before first rematching networks, put an inactivity timer without any request, this
10724 // allows {@code updateInactivityState} to update the state accordingly and prevent
10725 // tearing down for any {@code unneeded} evaluation in this period.
10726 // Note that the timer will not be rescheduled since the expiry time is
10727 // fixed after connection regardless of the network satisfying other requests or not.
10728 // But it will be removed as soon as the network satisfies a request for the first time.
10729 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10730 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010731 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010732
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010733 if (mTrackMultiNetworkActivities) {
10734 // Start tracking activity of this network.
10735 // This must be called before rematchAllNetworksAndRequests since the network
10736 // should be tracked when the network becomes the default network.
10737 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10738 // can be triggered later if this network becomes the default network.
10739 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10740 }
10741
Paul Jensen05e85ee2014-09-11 11:00:39 -040010742 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010743 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010744
10745 // This has to happen after matching the requests, because callbacks are just requests.
10746 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010747 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010748 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010749 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010750 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010751 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010752 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010753 if (networkAgent.isVPN()) {
10754 // As the active or bound network changes for apps, broadcast the default proxy, as
10755 // apps may need to update their proxy data. This is called after disconnecting from
10756 // VPN to make sure we do not broadcast the old proxy data.
10757 // TODO(b/122649188): send the broadcast only to VPN users.
10758 mProxyTracker.sendProxyBroadcast();
10759 }
Chalard Jean254bd162022-08-25 13:04:51 +090010760 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10761 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010762 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010763 }
10764 }
10765
Chalard Jean28018572020-12-21 18:36:52 +090010766 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010767 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10768 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010769 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010770 }
10771
Erik Kline99f301b2017-02-15 19:59:17 +090010772 // Notify only this one new request of the current state. Transfer all the
10773 // current state by calling NetworkCapabilities and LinkProperties callbacks
10774 // so that callers can be guaranteed to have as close to atomicity in state
10775 // transfer as can be supported by this current API.
10776 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010777 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010778 if (nri.mPendingIntent != null) {
10779 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10780 // Attempt no subsequent state pushes where intents are involved.
10781 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010782 }
Erik Kline99f301b2017-02-15 19:59:17 +090010783
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010784 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010785 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010786 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10787 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10788 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010789 }
10790
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010791 // Notify the requests on this NAI that the network is now lingered.
10792 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010793 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010794 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10795 }
10796
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010797 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10798 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10799 return vpnBlocked
10800 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10801 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10802 }
10803
10804 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10805 if (blockedReasons == BLOCKED_REASON_NONE) {
10806 mUidBlockedReasons.delete(uid);
10807 } else {
10808 mUidBlockedReasons.put(uid, blockedReasons);
10809 }
10810 }
10811
junyulaif2c67e42018-08-07 19:50:45 +080010812 /**
10813 * Notify of the blocked state apps with a registered callback matching a given NAI.
10814 *
10815 * Unlike other callbacks, blocked status is different between each individual uid. So for
10816 * any given nai, all requests need to be considered according to the uid who filed it.
10817 *
10818 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010819 * @param oldMetered True if the previous network capabilities were metered.
10820 * @param newMetered True if the current network capabilities are metered.
10821 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10822 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010823 */
10824 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010825 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10826 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010827
10828 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10829 NetworkRequest nr = nai.requestAt(i);
10830 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010831
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010832 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10833 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10834 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010835 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010836 : oldVpnBlocked;
10837
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010838 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10839 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10840 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010841 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010842 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010843 }
10844 }
10845 }
10846
10847 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010848 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010849 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010850 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010851 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010852 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010853 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010854 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010855 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010856
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010857 final int oldBlockedState = getBlockedState(
10858 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10859 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10860 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010861 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010862 }
junyulaif2c67e42018-08-07 19:50:45 +080010863 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10864 NetworkRequest nr = nai.requestAt(i);
10865 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010866 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010867 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10868 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010869 }
10870 }
10871 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010872 }
10873
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010874 @VisibleForTesting
10875 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010876 // The NetworkInfo we actually send out has no bearing on the real
10877 // state of affairs. For example, if the default connection is mobile,
10878 // and a request for HIPRI has just gone away, we need to pretend that
10879 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10880 // the state to DISCONNECTED, even though the network is of type MOBILE
10881 // and is still connected.
10882 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10883 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010884 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010885 if (state != DetailedState.DISCONNECTED) {
10886 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010887 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010888 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010889 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010890 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10891 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10892 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10893 if (info.isFailover()) {
10894 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10895 nai.networkInfo.setFailover(false);
10896 }
10897 if (info.getReason() != null) {
10898 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10899 }
10900 if (info.getExtraInfo() != null) {
10901 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10902 }
10903 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010904 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010905 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010906 if (newDefaultAgent != null) {
10907 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10908 newDefaultAgent.networkInfo);
10909 } else {
10910 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10911 }
10912 }
10913 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10914 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010915 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010916 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010917 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010918 }
10919 }
10920 }
10921
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010922 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010923 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010924 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010925 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010926 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010927 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10928 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010929 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10930 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010931 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010932 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010933 } else {
10934 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10935 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010936 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010937 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010938
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010939 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10940 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10941 }
10942
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010943 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010944 * Returns the list of all interfaces that could be used by network traffic that does not
10945 * explicitly specify a network. This includes the default network, but also all VPNs that are
10946 * currently connected.
10947 *
10948 * Must be called on the handler thread.
10949 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010950 @NonNull
10951 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010952 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010953 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010954 final Set<Integer> activeNetIds = new ArraySet<>();
10955 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10956 if (nri.isBeingSatisfied()) {
10957 activeNetIds.add(nri.getSatisfier().network().netId);
10958 }
10959 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010960 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010961 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010962 defaultNetworks.add(nai.network);
10963 }
10964 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010965 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010966 }
10967
10968 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010969 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10970 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010971 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010972 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010973 ensureRunningOnConnectivityServiceThread();
10974 String activeIface = null;
10975 LinkProperties activeLinkProperties = getActiveLinkProperties();
10976 if (activeLinkProperties != null) {
10977 activeIface = activeLinkProperties.getInterfaceName();
10978 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010979
junyulai2050bed2021-01-23 09:46:34 +080010980 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010981 try {
junyulaide41fc22021-01-22 22:46:01 +080010982 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010983 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010984 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10985 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010986 } catch (Exception ignored) {
10987 }
10988 }
10989
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010990 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010991 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010992 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010993 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010994 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010995
10996 if (!TextUtils.isEmpty(settingUrl)) {
10997 return settingUrl;
10998 }
10999
11000 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011001 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011002 if (!TextUtils.isEmpty(settingUrl)) {
11003 return settingUrl;
11004 }
11005
11006 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080011007 }
11008
11009 @Override
junyulai070f9ff2019-01-16 20:23:34 +080011010 public void startNattKeepalive(Network network, int intervalSeconds,
11011 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011012 enforceKeepalivePermission();
11013 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080011014 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000011015 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
11016 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000011017 // false and set the underpinned network to null because there is no way and no
11018 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
11019 // deprecated method.
11020 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011021 }
11022
11023 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011024 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080011025 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000011026 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070011027 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080011028 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011029 mKeepaliveTracker.startNattKeepalive(
11030 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000011031 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
11032 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070011033 } finally {
11034 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11035 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011036 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11037 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011038 }
11039 }
junyulaid05a1922019-01-15 11:32:44 +080011040 }
11041
11042 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011043 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080011044 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070011045 try {
11046 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080011047 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011048 mKeepaliveTracker.startTcpKeepalive(
11049 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
11050 } finally {
11051 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11052 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011053 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11054 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011055 }
11056 }
junyulai0835a1e2019-01-08 20:04:33 +080011057 }
11058
11059 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011060 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011061 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011062 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
11063 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011064 }
11065
11066 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090011067 public int[] getSupportedKeepalives() {
11068 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
11069 // Backwards compatibility with CTS 13
11070 android.Manifest.permission.QUERY_ALL_PACKAGES);
11071
11072 return BinderUtils.withCleanCallingIdentity(() ->
11073 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
11074 }
11075
11076 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070011077 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080011078 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070011079
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011080 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080011081 final long token = Binder.clearCallingIdentity();
11082 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011083 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
11084 UserHandle.getUserHandleForUid(uid))) {
11085 return;
11086 }
11087
Heemin Seogdb8489d2019-06-12 09:21:44 -070011088 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
11089 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011090
11091 // Turn airplane mode off
11092 setAirplaneMode(false);
11093
11094 // restore private DNS settings to default mode (opportunistic)
11095 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
11096 UserHandle.getUserHandleForUid(uid))) {
11097 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
11098 PRIVATE_DNS_MODE_OPPORTUNISTIC);
11099 }
11100
11101 Settings.Global.putString(mContext.getContentResolver(),
11102 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080011103 } finally {
11104 Binder.restoreCallingIdentity(token);
11105 }
Stuart Scottd5463642015-04-02 18:00:02 -070011106 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040011107
Ricky Wai7097cc92018-01-23 04:09:45 +000011108 @Override
11109 public byte[] getNetworkWatchlistConfigHash() {
11110 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
11111 if (nwm == null) {
11112 loge("Unable to get NetworkWatchlistManager");
11113 return null;
11114 }
11115 // Redirect it to network watchlist service to access watchlist file and calculate hash.
11116 return nwm.getWatchlistConfigHash();
11117 }
11118
Hugo Benichibe0c7652016-05-31 16:28:06 +090011119 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090011120 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080011121 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090011122 }
Hugo Benichif4210292017-04-21 15:07:12 +090011123
11124 private static boolean toBool(int encodedBoolean) {
11125 return encodedBoolean != 0; // Only 0 means false.
11126 }
11127
11128 private static int encodeBool(boolean b) {
11129 return b ? 1 : 0;
11130 }
mswest4632928412018-03-12 10:34:34 -070011131
11132 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011133 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
11134 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
11135 @NonNull String[] args) {
11136 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11137 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011138 }
11139
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011140 private Boolean parseBooleanArgument(final String arg) {
11141 if ("true".equals(arg)) {
11142 return true;
11143 } else if ("false".equals(arg)) {
11144 return false;
11145 } else {
11146 return null;
11147 }
11148 }
11149
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011150 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070011151 @Override
11152 public int onCommand(String cmd) {
11153 if (cmd == null) {
11154 return handleDefaultCommands(cmd);
11155 }
11156 final PrintWriter pw = getOutPrintWriter();
11157 try {
11158 switch (cmd) {
11159 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011160 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11161 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011162 final String action = getNextArg();
11163 if ("enable".equals(action)) {
11164 setAirplaneMode(true);
11165 return 0;
11166 } else if ("disable".equals(action)) {
11167 setAirplaneMode(false);
11168 return 0;
11169 } else if (action == null) {
11170 final ContentResolver cr = mContext.getContentResolver();
11171 final int enabled = Settings.Global.getInt(cr,
11172 Settings.Global.AIRPLANE_MODE_ON);
11173 pw.println(enabled == 0 ? "disabled" : "enabled");
11174 return 0;
11175 } else {
11176 onHelp();
11177 return -1;
11178 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011179 case "set-chain3-enabled": {
11180 final Boolean enabled = parseBooleanArgument(getNextArg());
11181 if (null == enabled) {
11182 onHelp();
11183 return -1;
11184 }
11185 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11186 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11187 enabled);
11188 return 0;
11189 }
11190 case "get-chain3-enabled": {
11191 final boolean chainEnabled = getFirewallChainEnabled(
11192 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11193 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11194 return 0;
11195 }
11196 case "set-package-networking-enabled": {
11197 final Boolean enabled = parseBooleanArgument(getNextArg());
11198 final String packageName = getNextArg();
11199 if (null == enabled || null == packageName) {
11200 onHelp();
11201 return -1;
11202 }
11203 // Throws NameNotFound if the package doesn't exist.
11204 final int appId = setPackageFirewallRule(
11205 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11206 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11207 final String msg = (enabled ? "Enabled" : "Disabled")
11208 + " networking for " + packageName + ", appId " + appId;
11209 Log.i(TAG, msg);
11210 pw.println(msg);
11211 return 0;
11212 }
11213 case "get-package-networking-enabled": {
11214 final String packageName = getNextArg();
11215 final int rule = getPackageFirewallRule(
11216 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11217 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11218 pw.println(packageName + ":" + "allow");
11219 } else if (FIREWALL_RULE_DENY == rule) {
11220 pw.println(packageName + ":" + "deny");
11221 } else {
11222 throw new IllegalStateException("Unknown rule " + rule + " for package "
11223 + packageName);
11224 }
11225 return 0;
11226 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011227 case "reevaluate":
11228 // Usage : adb shell cmd connectivity reevaluate <netId>
11229 // If netId is omitted, then reevaluate the default network
11230 final String netId = getNextArg();
11231 final NetworkAgentInfo nai;
11232 if (null == netId) {
11233 // Note that the command is running on the wrong thread to call this,
11234 // so this could in principle return stale data. But it can't crash.
11235 nai = getDefaultNetwork();
11236 } else {
11237 // If netId can't be parsed, this throws NumberFormatException, which
11238 // is passed back to adb who prints it.
11239 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11240 }
11241 if (null == nai) {
11242 pw.println("Unknown network (net ID not found or no default network)");
11243 return 0;
11244 }
11245 Log.d(TAG, "Reevaluating network " + nai.network);
11246 reportNetworkConnectivity(nai.network, !nai.isValidated());
11247 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011248 case "bpf-get-cgroup-program-id": {
11249 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11250 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11251 // for more detail.
11252 // If type can't be parsed, this throws NumberFormatException, which
11253 // is passed back to adb who prints it.
11254 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011255 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011256 pw.println(ret);
11257 return 0;
11258 }
mswest4632928412018-03-12 10:34:34 -070011259 default:
11260 return handleDefaultCommands(cmd);
11261 }
11262 } catch (Exception e) {
11263 pw.println(e);
11264 }
11265 return -1;
11266 }
11267
11268 @Override
11269 public void onHelp() {
11270 PrintWriter pw = getOutPrintWriter();
11271 pw.println("Connectivity service commands:");
11272 pw.println(" help");
11273 pw.println(" Print this help text.");
11274 pw.println(" airplane-mode [enable|disable]");
11275 pw.println(" Turn airplane mode on or off.");
11276 pw.println(" airplane-mode");
11277 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011278 pw.println(" set-chain3-enabled [true|false]");
11279 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11280 pw.println(" get-chain3-enabled");
11281 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11282 pw.println(" set-package-networking-enabled [true|false] [package name]");
11283 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11284 + " no effect if the chain is disabled.");
11285 pw.println(" get-package-networking-enabled [package name]");
11286 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011287 }
11288 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011289
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011290 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011291 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11292 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11293 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011294 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011295 }
11296
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011297 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11298 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011299 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11300 final TransportInfo newInfo = nc.getTransportInfo();
11301 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11302 return;
11303 }
11304 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011305 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011306 }
11307 }
11308
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011309 /**
11310 * @param connectionInfo the connection to resolve.
11311 * @return {@code uid} if the connection is found and the app has permission to observe it
11312 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11313 * connection is not found.
11314 */
11315 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011316 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11317 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11318 }
11319
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011320 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011321 connectionInfo.local, connectionInfo.remote);
11322
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011323 if (uid == INVALID_UID) return uid; // Not found.
11324
11325 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11326 // VPN, if any, that applies to the UID that owns the connection.
11327 if (checkNetworkStackPermission()) return uid;
11328
11329 final NetworkAgentInfo vpn = getVpnForUid(uid);
11330 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011331 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011332 return INVALID_UID;
11333 }
11334
11335 return uid;
11336 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011337
Benedict Wong493e04b2018-11-09 14:45:34 -080011338 /**
11339 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11340 *
11341 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11342 */
11343 @Override
11344 public IBinder startOrGetTestNetworkService() {
11345 synchronized (mTNSLock) {
11346 TestNetworkService.enforceTestNetworkPermissions(mContext);
11347
11348 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011349 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011350 }
11351
11352 return mTNS;
11353 }
11354 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011355
Cody Kesting73708bf2019-12-18 10:57:50 -080011356 /**
11357 * Handler used for managing all Connectivity Diagnostics related functions.
11358 *
11359 * @see android.net.ConnectivityDiagnosticsManager
11360 *
11361 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11362 */
11363 @VisibleForTesting
11364 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011365 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11366
Cody Kesting73708bf2019-12-18 10:57:50 -080011367 /**
11368 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11369 * android.net.ConnectivityDiagnosticsManager}.
11370 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11371 * NetworkRequestInfo to be registered
11372 */
11373 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11374
11375 /**
11376 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11377 * android.net.ConnectivityDiagnosticsManager}.
11378 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11379 * arg1 = the uid of the caller
11380 */
11381 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11382
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011383 /**
11384 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011385 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011386 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11387 * NetworkMonitor.
11388 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011389 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011390 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011391
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011392 /**
11393 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11394 * been detected on the network.
11395 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11396 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11397 * arg2 = NetID.
11398 * data = PersistableBundle of extras passed from NetworkMonitor.
11399 */
11400 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11401
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011402 /**
11403 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11404 * the platform. This event will invoke {@link
11405 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11406 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011407 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011408 */
11409 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11410
Cody Kesting73708bf2019-12-18 10:57:50 -080011411 private ConnectivityDiagnosticsHandler(Looper looper) {
11412 super(looper);
11413 }
11414
11415 @Override
11416 public void handleMessage(Message msg) {
11417 switch (msg.what) {
11418 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11419 handleRegisterConnectivityDiagnosticsCallback(
11420 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11421 break;
11422 }
11423 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11424 handleUnregisterConnectivityDiagnosticsCallback(
11425 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11426 break;
11427 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011428 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011429 final ConnectivityReportEvent reportEvent =
11430 (ConnectivityReportEvent) msg.obj;
11431
Aaron Huang959d3642021-01-21 15:47:41 +080011432 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011433 break;
11434 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011435 case EVENT_DATA_STALL_SUSPECTED: {
11436 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011437 final Pair<Long, PersistableBundle> arg =
11438 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011439 if (nai == null) break;
11440
Aaron Huang959d3642021-01-21 15:47:41 +080011441 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011442 break;
11443 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011444 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011445 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011446 break;
11447 }
11448 default: {
11449 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11450 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011451 }
11452 }
11453 }
11454
11455 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11456 @VisibleForTesting
11457 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11458 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11459 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011460 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011461
11462 @VisibleForTesting
11463 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011464 @NonNull IConnectivityDiagnosticsCallback cb,
11465 @NonNull NetworkRequestInfo nri,
11466 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011467 mCb = cb;
11468 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011469 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011470 }
11471
11472 @Override
11473 public void binderDied() {
11474 log("ConnectivityDiagnosticsCallback IBinder died.");
11475 unregisterConnectivityDiagnosticsCallback(mCb);
11476 }
11477 }
11478
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011479 /**
11480 * Class used for sending information from {@link
11481 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11482 */
11483 private static class NetworkTestedResults {
11484 private final int mNetId;
11485 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011486 @Nullable private final String mRedirectUrl;
11487
11488 private NetworkTestedResults(
11489 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11490 mNetId = netId;
11491 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011492 mRedirectUrl = redirectUrl;
11493 }
11494 }
11495
11496 /**
11497 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11498 * ConnectivityDiagnosticsHandler}.
11499 */
11500 private static class ConnectivityReportEvent {
11501 private final long mTimestampMillis;
11502 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011503 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011504
Aaron Huang959d3642021-01-21 15:47:41 +080011505 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11506 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011507 mTimestampMillis = timestampMillis;
11508 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011509 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011510 }
11511 }
11512
Cody Kestingf1120be2020-08-03 18:01:40 -070011513 /**
11514 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11515 * ConnectivityDiagnosticsHandler}.
11516 */
11517 private static class ReportedNetworkConnectivityInfo {
11518 public final boolean hasConnectivity;
11519 public final boolean isNetworkRevalidating;
11520 public final int reporterUid;
11521 @NonNull public final NetworkAgentInfo nai;
11522
11523 private ReportedNetworkConnectivityInfo(
11524 boolean hasConnectivity,
11525 boolean isNetworkRevalidating,
11526 int reporterUid,
11527 @NonNull NetworkAgentInfo nai) {
11528 this.hasConnectivity = hasConnectivity;
11529 this.isNetworkRevalidating = isNetworkRevalidating;
11530 this.reporterUid = reporterUid;
11531 this.nai = nai;
11532 }
11533 }
11534
Cody Kesting73708bf2019-12-18 10:57:50 -080011535 private void handleRegisterConnectivityDiagnosticsCallback(
11536 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11537 ensureRunningOnConnectivityServiceThread();
11538
11539 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011540 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011541 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11542
James Mattis64b8b0f2020-11-24 17:40:49 -080011543 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11544 // confusing for these networks to change when an NRI is satisfied in another layer.
11545 if (nri.isMultilayerRequest()) {
11546 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11547 + "network requests.");
11548 }
11549
Cody Kesting73708bf2019-12-18 10:57:50 -080011550 // This means that the client registered the same callback multiple times. Do
11551 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011552 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011553 if (VDBG) log("Diagnostics callback is already registered");
11554
11555 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11556 // incremented when the NetworkRequestInfo is created as part of
11557 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011558 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011559 return;
11560 }
11561
Cody Kesting31f1ff62020-03-05 10:46:02 -080011562 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011563
11564 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011565 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011566 } catch (RemoteException e) {
11567 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011568 return;
11569 }
11570
11571 // Once registered, provide ConnectivityReports for matching Networks
11572 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11573 synchronized (mNetworkForNetId) {
11574 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11575 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011576 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11577 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011578 matchingNetworks.add(nai);
11579 }
11580 }
11581 }
11582 for (final NetworkAgentInfo nai : matchingNetworks) {
11583 final ConnectivityReport report = nai.getConnectivityReport();
11584 if (report == null) {
11585 continue;
11586 }
11587 if (!checkConnectivityDiagnosticsPermissions(
11588 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11589 continue;
11590 }
11591
11592 try {
11593 cb.onConnectivityReportAvailable(report);
11594 } catch (RemoteException e) {
11595 // Exception while sending the ConnectivityReport. Move on to the next network.
11596 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011597 }
11598 }
11599
11600 private void handleUnregisterConnectivityDiagnosticsCallback(
11601 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11602 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011603 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011604
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011605 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11606 mConnectivityDiagnosticsCallbacks.remove(iCb);
11607 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011608 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11609 return;
11610 }
11611
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011612 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011613
Cody Kesting70fa2b22020-12-02 12:16:56 -080011614 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11615 // (if the Binder died)
11616 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11617 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011618 return;
11619 }
11620
Cody Kesting46cb1672020-03-04 13:35:20 -080011621 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11622 // incremented when the NetworkRequestInfo is created as part of
11623 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011624 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011625
Cody Kesting31f1ff62020-03-05 10:46:02 -080011626 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011627 }
11628
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011629 private void handleNetworkTestedWithExtras(
11630 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11631 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011632 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011633 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011634 final ConnectivityReport report =
11635 new ConnectivityReport(
11636 reportEvent.mNai.network,
11637 reportEvent.mTimestampMillis,
11638 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011639 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011640 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011641 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011642
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011643 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011644 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011645 for (final IConnectivityDiagnosticsCallback cb : results) {
11646 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011647 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011648 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011649 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011650 }
11651 }
11652 }
11653
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011654 private void handleDataStallSuspected(
11655 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11656 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011657 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011658 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011659 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011660 new DataStallReport(
11661 nai.network,
11662 timestampMillis,
11663 detectionMethod,
11664 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011665 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011666 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011667 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011668 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011669 for (final IConnectivityDiagnosticsCallback cb : results) {
11670 try {
11671 cb.onDataStallSuspected(report);
11672 } catch (RemoteException ex) {
11673 loge("Error invoking onDataStallSuspected", ex);
11674 }
11675 }
11676 }
11677
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011678 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011679 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11680 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11681 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11682
11683 // If the Network is being re-validated as a result of this call to
11684 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11685 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011686 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011687 getMatchingPermissionedCallbacks(
11688 nai,
11689 reportedNetworkConnectivityInfo.isNetworkRevalidating
11690 ? Process.INVALID_UID
11691 : reportedNetworkConnectivityInfo.reporterUid);
11692
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011693 for (final IConnectivityDiagnosticsCallback cb : results) {
11694 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011695 cb.onNetworkConnectivityReported(
11696 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011697 } catch (RemoteException ex) {
11698 loge("Error invoking onNetworkConnectivityReported", ex);
11699 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011700
11701 // If the Network isn't re-validating, also provide the cached report. If there is no
11702 // cached report, the Network is still being validated and a report will be sent once
11703 // validation is complete. Note that networks which never undergo validation will still
11704 // have a cached ConnectivityReport with RESULT_SKIPPED.
11705 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11706 try {
11707 cb.onConnectivityReportAvailable(cachedReport);
11708 } catch (RemoteException ex) {
11709 loge("Error invoking onConnectivityReportAvailable", ex);
11710 }
11711 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011712 }
11713 }
11714
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011715 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011716 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11717 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011718 sanitized.setUids(null);
11719 sanitized.setAdministratorUids(new int[0]);
11720 sanitized.setOwnerUid(Process.INVALID_UID);
11721 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011722 }
11723
Cody Kestingf1120be2020-08-03 18:01:40 -070011724 /**
11725 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11726 *
11727 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11728 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011729 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011730 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011731 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011732 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011733 mConnectivityDiagnosticsCallbacks.entrySet()) {
11734 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11735 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011736
James Mattis64b8b0f2020-11-24 17:40:49 -080011737 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011738 if (!nai.satisfies(nri.mRequests.get(0))) {
11739 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011740 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011741
11742 // UID for this callback must either be:
11743 // - INVALID_UID (which sends callbacks to all UIDs), or
11744 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11745 // notified as a result)
11746 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11747 continue;
11748 }
11749
11750 if (!checkConnectivityDiagnosticsPermissions(
11751 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11752 continue;
11753 }
11754
11755 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011756 }
11757 return results;
11758 }
11759
Cody Kesting7474f672021-05-11 14:22:40 -070011760 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11761 @NonNull NetworkAgentInfo nai) {
11762 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11763 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11764 }
11765
Cody Kesting160ef392021-05-05 13:17:22 -070011766 private boolean hasLocationPermission(String packageName, int uid) {
11767 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11768 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11769 // call in a try-catch.
11770 try {
11771 if (!mLocationPermissionChecker.checkLocationPermission(
11772 packageName, null /* featureId */, uid, null /* message */)) {
11773 return false;
11774 }
11775 } catch (SecurityException e) {
11776 return false;
11777 }
11778
11779 return true;
11780 }
11781
11782 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11783 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011784 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011785 && virtual.networkCapabilities.getOwnerUid() == uid
11786 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11787 return true;
11788 }
11789 }
11790
11791 return false;
11792 }
11793
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011794 @VisibleForTesting
11795 boolean checkConnectivityDiagnosticsPermissions(
11796 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11797 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11798 return true;
11799 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011800 if (mAllowSysUiConnectivityReports
Chris Göllnercc962022023-12-26 09:55:32 +000011801 && checkSystemBarServicePermission(callbackPid, callbackUid)) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011802 return true;
11803 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011804
Cody Kesting160ef392021-05-05 13:17:22 -070011805 // Administrator UIDs also contains the Owner UID
11806 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11807 if (!CollectionUtils.contains(administratorUids, callbackUid)
11808 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011809 return false;
11810 }
11811
Cody Kesting7474f672021-05-11 14:22:40 -070011812 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11813 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011814 }
11815
Cody Kestingd199a9d2019-12-17 12:55:28 -080011816 @Override
11817 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011818 @NonNull IConnectivityDiagnosticsCallback callback,
11819 @NonNull NetworkRequest request,
11820 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011821 Objects.requireNonNull(callback, "callback must not be null");
11822 Objects.requireNonNull(request, "request must not be null");
11823 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11824
Cody Kesting73708bf2019-12-18 10:57:50 -080011825 if (request.legacyType != TYPE_NONE) {
11826 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11827 + " Please use NetworkCapabilities instead.");
11828 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011829 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011830 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011831
11832 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11833 // and administrator uids to be safe.
11834 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011835 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011836
11837 final NetworkRequest requestWithId =
11838 new NetworkRequest(
11839 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11840
11841 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11842 //
11843 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11844 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11845 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011846 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011847 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011848 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011849
11850 mConnectivityDiagnosticsHandler.sendMessage(
11851 mConnectivityDiagnosticsHandler.obtainMessage(
11852 ConnectivityDiagnosticsHandler
11853 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11854 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011855 }
11856
11857 @Override
11858 public void unregisterConnectivityDiagnosticsCallback(
11859 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011860 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011861 mConnectivityDiagnosticsHandler.sendMessage(
11862 mConnectivityDiagnosticsHandler.obtainMessage(
11863 ConnectivityDiagnosticsHandler
11864 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011865 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011866 0,
11867 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011868 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011869
Yan Yanfe96dde2022-12-05 23:00:01 +000011870 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11871 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11872 if (underlyingNetworks == null) return false;
11873
11874 for (Network network : underlyingNetworks) {
11875 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11876 return true;
11877 }
11878 }
11879 return false;
11880 }
11881
Cody Kestingf53a0752020-04-15 12:33:28 -070011882 @Override
11883 public void simulateDataStall(int detectionMethod, long timestampMillis,
11884 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011885 Objects.requireNonNull(network, "network must not be null");
11886 Objects.requireNonNull(extras, "extras must not be null");
11887
paulhu3ffffe72021-09-16 10:15:22 +080011888 enforceAnyPermissionOf(mContext,
11889 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011890 android.Manifest.permission.NETWORK_STACK);
11891 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011892 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11893 throw new SecurityException(
11894 "Data Stall simulation is only possible for test networks or networks built on"
11895 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011896 }
11897
11898 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011899 if (nai == null
11900 || (nai.creatorUid != mDeps.getCallingUid()
11901 && nai.creatorUid != Process.SYSTEM_UID)) {
11902 throw new SecurityException(
11903 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011904 }
11905
Cody Kesting652e3ec2020-05-21 12:08:21 -070011906 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11907 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11908 // Data Stall information as a DataStallReportParcelable and passing to
11909 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11910 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011911 final DataStallReportParcelable p = new DataStallReportParcelable();
11912 p.timestampMillis = timestampMillis;
11913 p.detectionMethod = detectionMethod;
11914
11915 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11916 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11917 }
11918 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11919 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11920 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11921 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11922 }
11923
Serik Beketayevec8ad212020-12-07 22:43:07 -080011924 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011925 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011926
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011927 /**
11928 * Class to hold the information for network activity change event from idle timers
11929 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11930 */
11931 private static final class NetworkActivityParams {
11932 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011933 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
11934 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011935 public final int label;
11936 public final long timestampNs;
11937 // Uid represents the uid that was responsible for waking the radio.
11938 // -1 for no uid and uid is -1 if isActive is false.
11939 public final int uid;
11940
11941 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11942 this.isActive = isActive;
11943 this.label = label;
11944 this.timestampNs = timestampNs;
11945 this.uid = uid;
11946 }
11947 }
11948
lucaslin66f44212021-02-23 01:12:55 +080011949 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11950 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011951 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011952 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011953 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11954 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011955 }
lucaslin37a16d92021-01-21 19:48:09 +080011956
11957 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011958 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011959 mHandler.post(() -> {
11960 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011961 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011962 }
11963 });
lucaslin37a16d92021-01-21 19:48:09 +080011964 }
11965
11966 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011967 public void onInterfaceRemoved(@NonNull String iface) {
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.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011971 }
11972 });
lucaslin66f44212021-02-23 01:12:55 +080011973 }
11974 }
11975
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011976 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080011977 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11978
11979 /**
11980 * Class used for updating network activity tracking with netd and notify network activity
11981 * changes.
11982 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011983 @VisibleForTesting
11984 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011985 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011986 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011987 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011988 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011989 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11990 new RemoteCallbackList<>();
11991 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011992 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011993 // If there is no default network, default network is considered active to keep the existing
11994 // behavior. Initial value is used until first connect to the default network.
11995 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011996 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011997 // Key is netId. Value is configured idle timer information.
11998 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011999 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012000 // Store netIds of Wi-Fi networks whose idletimers report that they are active
12001 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
12002 // Store netIds of cellular networks whose idletimers report that they are active
12003 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080012004
Chalard Jean46bfbf02022-02-02 00:56:25 +090012005 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080012006 public final int timeout;
12007 public final int transportType;
12008
12009 IdleTimerParams(int timeout, int transport) {
12010 this.timeout = timeout;
12011 this.transportType = transport;
12012 }
12013 }
12014
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012015 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012016 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012017 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080012018 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012019 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012020 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012021 }
12022
12023 private void ensureRunningOnConnectivityServiceThread() {
12024 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
12025 throw new IllegalStateException("Not running on ConnectivityService thread: "
12026 + Thread.currentThread().getName());
12027 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012028 }
12029
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012030 /**
12031 * Update network activity and call BatteryStats to update radio power state if the
12032 * mobile or Wi-Fi activity is changed.
12033 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
12034 * mobile network is active since BatteryStatsService only maintains a single power state
12035 * for the mobile network.
12036 * The Wi-Fi network is also the same.
12037 *
12038 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
12039 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
12040 * transports.
12041 */
12042 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
12043 final boolean isActive, final int uid) {
12044 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
12045 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
12046 + transportType);
12047 return;
12048 }
12049 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
12050 ? mActiveWifiNetworks : mActiveCellularNetworks;
12051
12052 final boolean wasEmpty = activeNetworks.isEmpty();
12053 if (isActive) {
12054 activeNetworks.add(netId);
12055 } else {
12056 activeNetworks.remove(netId);
12057 }
12058
12059 if (wasEmpty != activeNetworks.isEmpty()) {
12060 updateRadioPowerState(isActive, transportType, uid);
12061 }
12062 }
12063
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012064 private void handleDefaultNetworkActivity(final int transportType,
12065 final boolean isActive, final long timestampNs) {
12066 mIsDefaultNetworkActive = isActive;
12067 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
12068 isActive, timestampNs);
12069 if (isActive) {
12070 reportNetworkActive();
12071 }
12072 }
12073
12074 private void handleReportNetworkActivityWithNetIdLabel(
12075 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012076 final int netId = activityParams.label;
12077 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012078 if (idleTimerParams == null) {
12079 // This network activity change is not tracked anymore
12080 // This can happen if netd callback post activity change event message but idle
12081 // timer is removed before processing this message.
12082 return;
12083 }
12084 // TODO: if a network changes transports, storing the transport type in the
12085 // IdleTimerParams is not correct. Consider getting it from the network's
12086 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012087 final int transportType = idleTimerParams.transportType;
12088 maybeUpdateRadioPowerState(netId, transportType,
12089 activityParams.isActive, activityParams.uid);
12090
12091 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
12092 // This activity change is not for the default network.
12093 return;
12094 }
12095
12096 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012097 activityParams.timestampNs);
12098 }
12099
12100 private void handleReportNetworkActivityWithTransportTypeLabel(
12101 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012102 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012103 // This activity change is not for the current default network.
12104 // This can happen if netd callback post activity change event message but
12105 // the default network is lost before processing this message.
12106 return;
12107 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012108 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
12109 activityParams.timestampNs);
12110 }
12111
12112 /**
12113 * Handle network activity change
12114 */
12115 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
12116 ensureRunningOnConnectivityServiceThread();
12117 if (mTrackMultiNetworkActivities) {
12118 handleReportNetworkActivityWithNetIdLabel(activityParams);
12119 } else {
12120 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080012121 }
12122 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012123
lucaslin1193a5d2021-01-21 02:04:15 +080012124 private void reportNetworkActive() {
12125 final int length = mNetworkActivityListeners.beginBroadcast();
12126 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
12127 try {
12128 for (int i = 0; i < length; i++) {
12129 try {
12130 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
12131 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012132 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080012133 }
12134 }
12135 } finally {
12136 mNetworkActivityListeners.finishBroadcast();
12137 }
12138 }
12139
lucaslin1a8b4c62021-01-21 02:02:55 +080012140 // This is deprecated and only to support legacy use cases.
12141 private int transportTypeToLegacyType(int type) {
12142 switch (type) {
12143 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012144 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012145 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012146 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012147 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012148 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012149 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012150 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012151 default:
12152 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12153 }
12154 return ConnectivityManager.TYPE_NONE;
12155 }
12156
12157 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12158 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12159 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12160 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12161 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12162 final long ident = Binder.clearCallingIdentity();
12163 try {
12164 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12165 RECEIVE_DATA_ACTIVITY_CHANGE,
12166 null /* resultReceiver */,
12167 null /* scheduler */,
12168 0 /* initialCode */,
12169 null /* initialData */,
12170 null /* initialExtra */);
12171 } finally {
12172 Binder.restoreCallingIdentity(ident);
12173 }
12174 }
12175
12176 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012177 * Get idle timer label
12178 */
12179 @VisibleForTesting
12180 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12181 final int netId, final int transportType) {
12182 return trackMultiNetworkActivities ? netId : transportType;
12183 }
12184
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012185 private boolean maybeCreateIdleTimer(
12186 String iface, int netId, int timeout, int transportType) {
12187 if (timeout <= 0 || iface == null) return false;
12188 try {
12189 final String label = Integer.toString(getIdleTimerLabel(
12190 mTrackMultiNetworkActivities, netId, transportType));
12191 mNetd.idletimerAddInterface(iface, timeout, label);
12192 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12193 return true;
12194 } catch (Exception e) {
12195 loge("Exception in createIdleTimer", e);
12196 return false;
12197 }
12198 }
12199
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012200 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012201 * Setup data activity tracking for the given network.
12202 *
12203 * Every {@code setupDataActivityTracking} should be paired with a
12204 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012205 *
12206 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012207 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012208 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012209 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012210 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012211 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012212
12213 final int timeout;
12214 final int type;
12215
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012216 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12217 // Do not track VPN network.
12218 return false;
12219 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012220 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12221 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012222 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012223 10);
12224 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12225 } else if (networkAgent.networkCapabilities.hasTransport(
12226 NetworkCapabilities.TRANSPORT_WIFI)) {
12227 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012228 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012229 15);
12230 type = NetworkCapabilities.TRANSPORT_WIFI;
12231 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012232 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012233 }
12234
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012235 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12236 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12237 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12238 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12239 // state only about a network that has an idletimer.
12240 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012241 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012242 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012243 }
12244
12245 /**
12246 * Remove data activity tracking when network disconnects.
12247 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012248 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12249 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012250 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012251 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012252 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12253
lucaslinb961efc2021-01-21 02:03:17 +080012254 if (iface == null) return;
12255
12256 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012257 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12258 // Do not track VPN network.
12259 return;
12260 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012261 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12262 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12263 type = NetworkCapabilities.TRANSPORT_WIFI;
12264 } else {
12265 return; // do not track any other networks
12266 }
12267
12268 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012269 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012270 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012271 if (params == null) {
12272 // IdleTimer is not added if the configured timeout is 0 or negative value
12273 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012274 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012275 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012276 final String label = Integer.toString(getIdleTimerLabel(
12277 mTrackMultiNetworkActivities, netId, params.transportType));
12278 // The call fails silently if no idle timer setup for this interface
12279 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012280 } catch (Exception e) {
12281 // You shall not crash!
12282 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012283 }
12284 }
12285
Motomu Utsumi6225d572023-05-29 15:08:57 +090012286 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12287 boolean hasIdleTimer) {
12288 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012289 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012290 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012291 // If only the default network is tracked, callbacks are called only when the
12292 // network has the idle timer.
12293 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012294 reportNetworkActive();
12295 }
12296 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012297 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012298 // If there is no default network, default network is considered active to keep the
12299 // existing behavior.
12300 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012301 }
12302 }
12303
lucaslin1a8b4c62021-01-21 02:02:55 +080012304 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012305 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012306 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012307 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012308 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012309 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012310 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12311 // first connected and remove when the network is disconnected.
12312 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12313 // becomes the default network and remove when the network becomes no longer the default
12314 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012315 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012316 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012317 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012318 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012319 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012320 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012321 removeDataActivityTracking(oldNetwork);
12322 }
12323 }
lucaslinb961efc2021-01-21 02:03:17 +080012324
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012325 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012326 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12327 switch (transportType) {
12328 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012329 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012330 break;
12331 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012332 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012333 break;
12334 default:
12335 logw("Untracked transport type:" + transportType);
12336 }
12337 }
lucaslin1193a5d2021-01-21 02:04:15 +080012338
12339 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012340 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012341 }
12342
12343 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12344 mNetworkActivityListeners.register(l);
12345 }
12346
12347 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12348 mNetworkActivityListeners.unregister(l);
12349 }
lucaslin012f7a12021-01-21 02:04:35 +080012350
12351 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012352 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012353 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012354 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012355 pw.println("Idle timers:");
12356 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012357 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12358 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12359 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012360 pw.print(" timeout="); pw.print(params.timeout);
12361 pw.print(" type="); pw.println(params.transportType);
12362 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012363 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12364 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012365 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012366 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12367 // be accessed from handler thread, except dump(). As dump() is never called in
12368 // normal usage, it would be needlessly expensive to lock the collection only for
12369 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012370 // So catching the exception and logging.
12371 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012372 }
12373 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012374 }
James Mattis47db0582021-01-01 14:13:35 -080012375
Daniel Brightf9e945b2020-06-15 16:10:01 -070012376 /**
12377 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12378 *
12379 * @param socketInfo the socket information
12380 * @param callback the callback to register
12381 */
12382 @Override
12383 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12384 @NonNull final IQosCallback callback) {
12385 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12386 if (nai == null || nai.networkCapabilities == null) {
12387 try {
12388 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12389 } catch (final RemoteException ex) {
12390 loge("registerQosCallbackInternal: RemoteException", ex);
12391 }
12392 return;
12393 }
12394 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12395 }
12396
12397 /**
12398 * Register a {@link IQosCallback} with base {@link QosFilter}.
12399 *
12400 * @param filter the filter to register
12401 * @param callback the callback to register
12402 * @param nai the agent information related to the filter's network
12403 */
12404 @VisibleForTesting
12405 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12406 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012407 Objects.requireNonNull(filter, "filter must be non-null");
12408 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012409
12410 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012411 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12412 // on this network is unregistered when the app loses permission or b) no QoS
12413 // callbacks are sent for restricted networks unless the app currently has permission
12414 // to access restricted networks.
12415 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012416 }
12417 mQosCallbackTracker.registerCallback(callback, filter, nai);
12418 }
12419
12420 /**
12421 * Unregisters the given callback.
12422 *
12423 * @param callback the callback to unregister
12424 */
12425 @Override
12426 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012427 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012428 mQosCallbackTracker.unregisterCallback(callback);
12429 }
James Mattis47db0582021-01-01 14:13:35 -080012430
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012431 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12432 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12433 // Enterprise device can be fully managed like device owner and such use case
12434 // also should be supported. Calling app check for work profile and fully managed device
12435 // is already done in DevicePolicyManager.
12436 // This check is an extra caution to be sure device is fully managed or not.
12437 final UserManager um = mContext.getSystemService(UserManager.class);
12438 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12439 if (um.isManagedProfile(profile.getIdentifier())) {
12440 return true;
12441 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012442 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012443 return false;
12444 }
12445
James Mattis45d81842021-01-10 14:24:24 -080012446 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012447 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012448 *
12449 * See the documentation for the individual preferences for a description of the supported
12450 * behaviors.
12451 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012452 * @param profile If the device owner is set, any profile is allowed.
12453 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012454 * @param preferences the list of profile network preferences for the
12455 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012456 * @param listener an optional listener to listen for completion of the operation.
12457 */
12458 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012459 public void setProfileNetworkPreferences(
12460 @NonNull final UserHandle profile,
12461 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012462 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012463 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012464 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012465
12466 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012467 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12468 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12469 .build();
12470 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012471 }
12472
paulhu3ffffe72021-09-16 10:15:22 +080012473 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012474 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012475 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012476 }
12477 if (profile.getIdentifier() < 0) {
12478 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12479 + "UserHandle.CURRENT not supported)");
12480 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012481 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12482 throw new IllegalArgumentException("Profile must be a managed profile "
12483 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012484 }
paulhuaa0743d2021-05-26 21:56:03 +080012485
Chalard Jean0606fc82022-12-14 20:34:43 +090012486 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012487 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012488 for (final ProfileNetworkPreference preference : preferences) {
12489 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012490 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012491 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012492 switch (preference.getPreference()) {
12493 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12494 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012495 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012496 if (preference.getPreferenceEnterpriseId() != 0) {
12497 throw new IllegalArgumentException(
12498 "Invalid enterprise identifier in setProfileNetworkPreferences");
12499 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012500 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012501 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12502 blockingNonEnterprise = true;
12503 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012504 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12505 allowFallback = false;
12506 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012507 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012508 // This code is needed even though there is a check later on,
12509 // because isRangeAlreadyInPreferenceList assumes that every preference
12510 // has a UID list.
12511 if (hasDefaultPreference) {
12512 throw new IllegalArgumentException(
12513 "Default profile preference should not be set along with other "
12514 + "preference");
12515 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012516 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12517 throw new IllegalArgumentException(
12518 "Invalid enterprise identifier in setProfileNetworkPreferences");
12519 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012520 final Set<UidRange> uidRangeSet =
12521 getUidListToBeAppliedForNetworkPreference(profile, preference);
12522 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12523 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12524 } else {
12525 throw new IllegalArgumentException(
12526 "Overlapping uid range in setProfileNetworkPreferences");
12527 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012528 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012529 nc.addEnterpriseId(
12530 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012531 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12532 break;
12533 default:
12534 throw new IllegalArgumentException(
12535 "Invalid preference in setProfileNetworkPreferences");
12536 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012537 preferenceList.add(new ProfileNetworkPreferenceInfo(
12538 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012539 if (hasDefaultPreference && preferenceList.size() > 1) {
12540 throw new IllegalArgumentException(
12541 "Default profile preference should not be set along with other preference");
12542 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012543 }
12544 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012545 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012546 }
12547
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012548 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12549 @NonNull final UserHandle profile,
12550 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12551 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012552 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12553 profileNetworkPreference.getIncludedUids());
12554
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012555 if (uidRangeSet.size() > 0) {
12556 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12557 throw new IllegalArgumentException(
12558 "Allow uid range is outside the uid range of profile.");
12559 }
12560 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012561 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012562 profileNetworkPreference.getExcludedUids());
12563 if (disallowUidRangeSet.size() > 0) {
12564 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12565 throw new IllegalArgumentException(
12566 "disallow uid range is outside the uid range of profile.");
12567 }
12568 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12569 disallowUidRangeSet);
12570 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012571 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012572 uidRangeSet.add(profileUids);
12573 }
12574 }
12575 return uidRangeSet;
12576 }
12577
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012578 private boolean isEnterpriseIdentifierValid(
12579 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012580 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012581 return true;
12582 }
12583 return false;
12584 }
12585
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012586 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012587 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012588 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012589 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012590 // The NRI for a user should contain the request for capabilities.
12591 // If fallback to default network is needed then NRI should include
12592 // the request for the default network. Create an image of it to
12593 // have the correct UIDs in it (also a request can only be part of one NRI, because
12594 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012595 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12596 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012597 if (pref.allowFallback) {
12598 nrs.add(createDefaultInternetRequestForTransport(
12599 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12600 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012601 if (VDBG) {
12602 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12603 pref.capabilities.getUids()));
12604 }
12605
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012606 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012607 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012608 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012609 result.add(nri);
12610 }
12611 return result;
12612 }
12613
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012614 /**
12615 * Compare if the given UID range sets have the same UIDs.
12616 *
12617 */
12618 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012619 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012620 @NonNull Set<UidRange> uidRangeSet) {
12621 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12622 return false;
12623 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012624 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012625 if (UidRangeUtils.doesRangeSetOverlap(
12626 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12627 return true;
12628 }
12629 }
12630 return false;
12631 }
12632
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012633 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012634 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012635 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012636 /*
12637 * handleSetProfileNetworkPreference is always called for single user.
12638 * preferenceList only contains preferences for different uids within the same user
12639 * (enforced by getUidListToBeAppliedForNetworkPreference).
12640 * Clear all the existing preferences for the user before applying new preferences.
12641 *
12642 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012643 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12644 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012645 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12646 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012647
paulhu74128522021-09-28 02:29:03 +000012648 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12649 addPerAppDefaultNetworkRequests(
12650 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012651 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012652
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012653 // Finally, rematch.
12654 rematchAllNetworksAndRequests();
12655
12656 if (null != listener) {
12657 try {
12658 listener.onComplete();
12659 } catch (RemoteException e) {
12660 loge("Listener for setProfileNetworkPreference has died");
12661 }
12662 }
12663 }
12664
paulhu51f77dc2021-06-07 02:34:20 +000012665 @VisibleForTesting
12666 @NonNull
12667 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12668 @NonNull final Set<Integer> uids) {
12669 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12670 if (uids.size() == 0) {
12671 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12672 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12673 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12674 return nris;
12675 }
12676
12677 final List<NetworkRequest> requests = new ArrayList<>();
12678 // The NRI should be comprised of two layers:
12679 // - The request for the mobile network preferred.
12680 // - The request for the default network, for fallback.
12681 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012682 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012683 requests.add(createDefaultInternetRequestForTransport(
12684 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12685 final Set<UidRange> ranges = new ArraySet<>();
12686 for (final int uid : uids) {
12687 ranges.add(new UidRange(uid, uid));
12688 }
12689 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012690 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012691 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012692 return nris;
12693 }
12694
12695 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012696 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012697 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12698 addPerAppDefaultNetworkRequests(
12699 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012700 // Finally, rematch.
12701 rematchAllNetworksAndRequests();
12702 }
12703
Patrick Rohr2857ac42022-01-21 14:58:16 +010012704 private void handleIngressRateLimitChanged() {
12705 final long oldIngressRateLimit = mIngressRateLimit;
12706 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12707 mContext);
12708 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12709 if (canNetworkBeRateLimited(networkAgent)) {
12710 // If rate limit has previously been enabled, remove the old limit first.
12711 if (oldIngressRateLimit >= 0) {
12712 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12713 }
12714 if (mIngressRateLimit >= 0) {
12715 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12716 mIngressRateLimit);
12717 }
12718 }
12719 }
12720 }
12721
12722 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012723 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012724 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012725
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012726 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12727 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12728 // internet connectivity can be rate limited.
12729 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12730 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012731 return false;
12732 }
12733
12734 final String iface = networkAgent.linkProperties.getInterfaceName();
12735 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012736 // This may happen in tests, but if there is no interface then there is nothing that
12737 // can be rate limited.
12738 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012739 return false;
12740 }
12741 return true;
12742 }
12743
James Mattis45d81842021-01-10 14:24:24 -080012744 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012745 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12746 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012747 }
12748
12749 /**
12750 * Used by automotive devices to set the network preferences used to direct traffic at an
12751 * application level as per the given OemNetworkPreferences. An example use-case would be an
12752 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12753 * vehicle via a particular network.
12754 *
12755 * Calling this will overwrite the existing preference.
12756 *
James Mattisda32cfe2021-01-26 16:23:52 -080012757 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012758 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012759 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012760 */
James Mattis47db0582021-01-01 14:13:35 -080012761 @Override
James Mattis45d81842021-01-10 14:24:24 -080012762 public void setOemNetworkPreference(
12763 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012764 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012765
James Mattisfa270db2021-05-31 17:11:10 -070012766 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12767 // Only bypass the permission/device checks if this is a valid test request.
12768 if (isValidTestOemNetworkPreference(preference)) {
12769 enforceManageTestNetworksPermission();
12770 } else {
12771 enforceAutomotiveDevice();
12772 enforceOemNetworkPreferencesPermission();
12773 validateOemNetworkPreferences(preference);
12774 }
James Mattis45d81842021-01-10 14:24:24 -080012775
James Mattis45d81842021-01-10 14:24:24 -080012776 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12777 new Pair<>(preference, listener)));
12778 }
12779
James Mattisfa270db2021-05-31 17:11:10 -070012780 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012781 * Sets the specified UIDs to get/receive the VPN as the only default network.
12782 *
12783 * Calling this will overwrite the existing network preference for this session, and the
12784 * specified UIDs won't get any default network when no VPN is connected.
12785 *
12786 * @param session The VPN session which manages the passed UIDs.
12787 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12788 * setting for this session if the array is empty. Null is not allowed, the
12789 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12790 * @hide
12791 */
12792 @Override
12793 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12794 Objects.requireNonNull(ranges);
12795 enforceNetworkStackOrSettingsPermission();
12796 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12797 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12798 throw new IllegalArgumentException(
12799 "setVpnNetworkPreference: Passed UID ranges overlap");
12800 }
12801
12802 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12803 new VpnNetworkPreferenceInfo(session,
12804 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12805 }
12806
12807 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12808 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12809
12810 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12811 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12812
12813 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12814 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12815 // Finally, rematch.
12816 rematchAllNetworksAndRequests();
12817 }
12818
12819 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12820 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12821 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12822 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12823 final List<NetworkRequest> requests = new ArrayList<>();
12824 // Request VPN only, so other networks won't be the fallback options when VPN is not
12825 // connected temporarily.
12826 requests.add(createVpnRequest());
12827 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12828 setNetworkRequestUids(requests, uidRanges);
12829 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12830 }
12831 return nris;
12832 }
12833
12834 /**
James Mattisfa270db2021-05-31 17:11:10 -070012835 * Check the validity of an OEM network preference to be used for testing purposes.
12836 * @param preference the preference to validate
12837 * @return true if this is a valid OEM network preference test request.
12838 */
12839 private boolean isValidTestOemNetworkPreference(
12840 @NonNull final OemNetworkPreferences preference) {
12841 // Allow for clearing of an existing OemNetworkPreference used for testing.
12842 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12843 // changes after this check is complete. This is an unlikely scenario as calling of this API
12844 // is controlled by the OEM therefore the added complexity is not worth adding given those
12845 // circumstances. That said, it is an edge case to be aware of hence this comment.
12846 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12847 && isTestOemNetworkPreference(mOemNetworkPreferences);
12848 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12849 }
12850
12851 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12852 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12853 return prefMap.size() == 1
12854 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12855 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12856 }
12857
James Mattis45d81842021-01-10 14:24:24 -080012858 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12859 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12860 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012861 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12862 throw new IllegalArgumentException(
12863 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12864 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012865 }
12866 }
12867 }
12868
12869 private void handleSetOemNetworkPreference(
12870 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012871 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012872 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12873 if (DBG) {
12874 log("set OEM network preferences :" + preference.toString());
12875 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012876
James Mattiscb1e0362021-04-06 17:07:42 -070012877 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012878 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12879 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12880 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012881 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012882
12883 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012884 try {
12885 listener.onComplete();
12886 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012887 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012888 }
James Mattis45d81842021-01-10 14:24:24 -080012889 }
12890 }
12891
paulhu74128522021-09-28 02:29:03 +000012892 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012893 // Skip the requests which are set by other network preference. Because the uid range rules
12894 // should stay in netd.
12895 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012896 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012897 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012898 }
12899
James Mattis3ce3d3c2021-02-09 18:18:28 -080012900 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12901 ensureRunningOnConnectivityServiceThread();
12902 mDefaultNetworkRequests.addAll(nris);
12903 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12904 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012905 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012906 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12907 nrisToRegister.addAll(
12908 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12909 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012910 }
12911
12912 /**
12913 * All current requests that are tracking the default network need to be assessed as to whether
12914 * or not the current set of per-application default requests will be changing their default
12915 * network. If so, those requests will need to be updated so that they will send callbacks for
12916 * default network changes at the appropriate time. Additionally, those requests tracking the
12917 * default that were previously updated by this flow will need to be reassessed.
12918 * @return the nris which will need to be updated.
12919 */
12920 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12921 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12922 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12923 // same nri in the map's values for each of its NetworkRequest objects.
12924 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012925 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012926 // Include this nri if it is currently being tracked.
12927 if (isPerAppTrackedNri(nri)) {
12928 defaultCallbackRequests.add(nri);
12929 continue;
12930 }
12931 // We only track callbacks for requests tracking the default.
12932 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12933 continue;
12934 }
12935 // Include this nri if it will be tracked by the new per-app default requests.
12936 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012937 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012938 if (isNriGoingToBeTracked) {
12939 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012940 }
12941 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012942 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012943 }
12944
James Mattis3ce3d3c2021-02-09 18:18:28 -080012945 /**
12946 * Create nris for those network requests that are currently tracking the default network that
12947 * are being controlled by a per-application default.
12948 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12949 * foundation when creating the nri. Important items include the calling uid's original
12950 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12951 * requests are assumed to have already been validated as needing to be updated.
12952 * @return the Set of nris to use when registering network requests.
12953 */
12954 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12955 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12956 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12957 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12958 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012959 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012960
Chalard Jean9473c982021-07-29 20:03:04 +090012961 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012962 if (trackingNri == mDefaultRequest) {
12963 callbackRequestsToRegister.add(new NetworkRequestInfo(
12964 callbackRequest,
12965 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12966 continue;
12967 }
12968
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012969 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012970 callbackRequestsToRegister.add(new NetworkRequestInfo(
12971 callbackRequest,
12972 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012973 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012974 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012975 }
12976 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012977 }
12978
Chalard Jean17215832021-03-01 14:06:28 +090012979 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12980 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012981 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012982 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012983 }
12984 }
12985
James Mattis45d81842021-01-10 14:24:24 -080012986 /**
12987 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12988 */
12989 @VisibleForTesting
12990 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012991 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012992 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012993 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012994 final SparseArray<Set<Integer>> uids =
12995 createUidsFromOemNetworkPreferences(preference);
12996 for (int i = 0; i < uids.size(); i++) {
12997 final int key = uids.keyAt(i);
12998 final Set<Integer> value = uids.valueAt(i);
12999 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
13000 // No need to add an nri without any requests.
13001 if (0 == nri.mRequests.size()) {
13002 continue;
13003 }
13004 nris.add(nri);
13005 }
13006
13007 return nris;
13008 }
13009
13010 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
13011 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070013012 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080013013 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080013014 final List<UserHandle> users =
13015 mContext.getSystemService(UserManager.class).getUserHandles(true);
13016 if (null == users || users.size() == 0) {
13017 if (VDBG || DDBG) {
13018 log("No users currently available for setting the OEM network preference.");
13019 }
James Mattisb6b6a432021-06-01 22:30:36 -070013020 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080013021 }
James Mattis45d81842021-01-10 14:24:24 -080013022 for (final Map.Entry<String, Integer> entry :
13023 preference.getNetworkPreferences().entrySet()) {
13024 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070013025 // Add the rules for all users as this policy is device wide.
13026 for (final UserHandle user : users) {
13027 try {
13028 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
13029 if (!prefToUids.contains(pref)) {
13030 prefToUids.put(pref, new ArraySet<>());
13031 }
13032 prefToUids.get(pref).add(uid);
13033 } catch (PackageManager.NameNotFoundException e) {
13034 // Although this may seem like an error scenario, it is ok that uninstalled
13035 // packages are sent on a network preference as the system will watch for
13036 // package installations associated with this network preference and update
13037 // accordingly. This is done to minimize race conditions on app install.
13038 continue;
James Mattis45d81842021-01-10 14:24:24 -080013039 }
James Mattis45d81842021-01-10 14:24:24 -080013040 }
13041 }
James Mattisb6b6a432021-06-01 22:30:36 -070013042 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080013043 }
13044
13045 private NetworkRequestInfo createNriFromOemNetworkPreferences(
13046 @OemNetworkPreferences.OemNetworkPreference final int preference,
13047 @NonNull final Set<Integer> uids) {
13048 final List<NetworkRequest> requests = new ArrayList<>();
13049 // Requests will ultimately be evaluated by order of insertion therefore it matters.
13050 switch (preference) {
13051 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
13052 requests.add(createUnmeteredNetworkRequest());
13053 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070013054 requests.add(createDefaultInternetRequestForTransport(
13055 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080013056 break;
13057 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
13058 requests.add(createUnmeteredNetworkRequest());
13059 requests.add(createOemPaidNetworkRequest());
13060 break;
13061 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
13062 requests.add(createOemPaidNetworkRequest());
13063 break;
13064 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
13065 requests.add(createOemPrivateNetworkRequest());
13066 break;
James Mattisfa270db2021-05-31 17:11:10 -070013067 case OEM_NETWORK_PREFERENCE_TEST:
13068 requests.add(createUnmeteredNetworkRequest());
13069 requests.add(createTestNetworkRequest());
13070 requests.add(createDefaultRequest());
13071 break;
13072 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
13073 requests.add(createTestNetworkRequest());
13074 break;
James Mattis45d81842021-01-10 14:24:24 -080013075 default:
13076 // This should never happen.
13077 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
13078 + " called with invalid preference of " + preference);
13079 }
13080
James Mattisfa270db2021-05-31 17:11:10 -070013081 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090013082 for (final int uid : uids) {
13083 ranges.add(new UidRange(uid, uid));
13084 }
13085 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080013086 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080013087 }
13088
13089 private NetworkRequest createUnmeteredNetworkRequest() {
13090 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13091 .addCapability(NET_CAPABILITY_NOT_METERED)
13092 .addCapability(NET_CAPABILITY_VALIDATED);
13093 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
13094 }
13095
13096 private NetworkRequest createOemPaidNetworkRequest() {
13097 // NET_CAPABILITY_OEM_PAID is a restricted capability.
13098 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13099 .addCapability(NET_CAPABILITY_OEM_PAID)
13100 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13101 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13102 }
13103
13104 private NetworkRequest createOemPrivateNetworkRequest() {
13105 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
13106 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13107 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
13108 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13109 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13110 }
13111
13112 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070013113 final NetworkCapabilities netcap = new NetworkCapabilities();
13114 netcap.addCapability(NET_CAPABILITY_INTERNET);
13115 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
13116 return netcap;
13117 }
13118
13119 private NetworkRequest createTestNetworkRequest() {
13120 final NetworkCapabilities netcap = new NetworkCapabilities();
13121 netcap.clearAll();
13122 netcap.addTransportType(TRANSPORT_TEST);
13123 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080013124 }
James Mattis47db0582021-01-01 14:13:35 -080013125 }
markchien738ad912021-12-09 18:15:45 +080013126
Junyu Lai38c75032023-12-04 07:52:19 +000013127 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080013128 @Override
Junyu Laidf210362023-10-24 02:47:50 +000013129 public void setDataSaverEnabled(final boolean enable) {
13130 enforceNetworkStackOrSettingsPermission();
13131 try {
13132 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
13133 if (!ret) {
13134 throw new IllegalStateException("Error when changing iptables: " + enable);
13135 }
13136 } catch (RemoteException e) {
13137 // Lack of permission or binder errors.
13138 throw new IllegalStateException(e);
13139 }
Ken Chen24330172023-10-20 13:02:14 +080013140
13141 try {
13142 mBpfNetMaps.setDataSaverEnabled(enable);
13143 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13144 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13145 }
Junyu Laidf210362023-10-24 02:47:50 +000013146 }
13147
13148 @Override
markchien738ad912021-12-09 18:15:45 +080013149 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13150 enforceNetworkStackOrSettingsPermission();
13151
13152 try {
13153 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013154 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013155 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013156 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013157 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013158 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013159 throw new IllegalStateException(e);
13160 }
13161 }
13162
13163 @Override
13164 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13165 enforceNetworkStackOrSettingsPermission();
13166
13167 try {
13168 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013169 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013170 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013171 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013172 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013173 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013174 throw new IllegalStateException(e);
13175 }
13176 }
markchiene1561fa2021-12-09 22:00:56 +080013177
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013178 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13179 throws PackageManager.NameNotFoundException {
13180 final PackageManager pm = mContext.getPackageManager();
13181 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13182 if (appId < Process.FIRST_APPLICATION_UID) {
13183 throw new RuntimeException("Can't set package firewall rule for system app "
13184 + packageName + " with appId " + appId);
13185 }
13186 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13187 final int uid = uh.getUid(appId);
13188 setUidFirewallRule(chain, uid, rule);
13189 }
13190 return appId;
13191 }
13192
markchiene1561fa2021-12-09 22:00:56 +080013193 @Override
markchien3c04e662022-03-22 16:29:56 +080013194 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013195 enforceNetworkStackOrSettingsPermission();
13196
markchien3c04e662022-03-22 16:29:56 +080013197 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13198 int firewallRule = getFirewallRuleType(chain, rule);
13199
13200 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13201 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13202 }
13203
markchiene1561fa2021-12-09 22:00:56 +080013204 try {
markchien3c04e662022-03-22 16:29:56 +080013205 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013206 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013207 throw new IllegalStateException(e);
13208 }
13209 }
markchien98a6f952022-01-13 23:43:53 +080013210
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013211 private int getPackageFirewallRule(final int chain, final String packageName)
13212 throws PackageManager.NameNotFoundException {
13213 final PackageManager pm = mContext.getPackageManager();
13214 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13215 return getUidFirewallRule(chain, appId);
13216 }
13217
Motomu Utsumi900b8062023-01-19 16:16:49 +090013218 @Override
13219 public int getUidFirewallRule(final int chain, final int uid) {
13220 enforceNetworkStackOrSettingsPermission();
13221 return mBpfNetMaps.getUidRule(chain, uid);
13222 }
13223
markchien3c04e662022-03-22 16:29:56 +080013224 private int getFirewallRuleType(int chain, int rule) {
13225 final int defaultRule;
13226 switch (chain) {
13227 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013228 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13229 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013230 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013231 defaultRule = FIREWALL_RULE_ALLOW;
13232 break;
13233 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13234 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13235 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13236 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013237 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013238 defaultRule = FIREWALL_RULE_DENY;
13239 break;
13240 default:
13241 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13242 }
13243 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13244
13245 return rule;
13246 }
13247
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013248 private void closeSocketsForFirewallChainLocked(final int chain)
13249 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013250 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013251 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13252 // So, close all non-system socket owned by uids that are not explicitly allowed
13253 Set<Range<Integer>> ranges = new ArraySet<>();
13254 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13255 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13256 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13257 } else {
13258 // Denylist means the firewall allows all by default, uids must be explicitly denied
13259 // So, close socket owned by uids that are explicitly denied
13260 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13261 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13262 }
13263 }
13264
markchien98a6f952022-01-13 23:43:53 +080013265 @Override
13266 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13267 enforceNetworkStackOrSettingsPermission();
13268
13269 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013270 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013271 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013272 throw new IllegalStateException(e);
13273 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013274
Chalard Jeandf29a852023-05-29 17:02:43 +090013275 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013276 try {
13277 closeSocketsForFirewallChainLocked(chain);
13278 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13279 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13280 }
13281 }
markchien98a6f952022-01-13 23:43:53 +080013282 }
13283
markchien00a0bed2022-01-13 23:46:13 +080013284 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013285 public boolean getFirewallChainEnabled(final int chain) {
13286 enforceNetworkStackOrSettingsPermission();
13287
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013288 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013289 }
13290
13291 @Override
markchien00a0bed2022-01-13 23:46:13 +080013292 public void replaceFirewallChain(final int chain, final int[] uids) {
13293 enforceNetworkStackOrSettingsPermission();
13294
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013295 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013296 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013297
13298 @Override
13299 public IBinder getCompanionDeviceManagerProxyService() {
13300 enforceNetworkStackPermission(mContext);
13301 return mCdmps;
13302 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013303
13304 @Override
13305 public IBinder getRoutingCoordinatorService() {
13306 enforceNetworkStackPermission(mContext);
13307 return mRoutingCoordinatorService;
13308 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013309}